Saturday, March 12, 2011

IOC - Beginner level implentation of constructor Dependency Injection.



So , we have Registration Module which maintains a mapping of abstract entity type with their implementation (concrete) types, and then we have abstract entity mapping to a concrete instance, which is created on runtime (lazy) by resolving is there is already an existing instance, if not found, then create a new instance by resolving the types which are needed by the parameters of constructor and creating them, and then finally invoking the contructor.

Let's get our hands dirty..

public class RegistrationModule { private readonly Dictionary _abstract2ConcreteTypeMap; private readonly Dictionary _abstract2InstanceMap; public RegistrationModule() { _abstract2ConcreteTypeMap = new Dictionary(); _abstract2InstanceMap = new Dictionary(); } public void Load() { _abstract2InstanceMap.Clear(); _abstract2ConcreteTypeMap.Clear(); Register&lt;IServiceProvider,ServiceProvier&gt;(); Register<IBusineesLogic,BusinessLogic>(); Register(); }  ... }
This would be the raw structure of the registration module. And then we need a IOC implementation logic which uses these registration modules to find if an instance is already created for a type? if yes, then resolve it and send back to user. If not, then read the get mapping of the concrete class of the interface that user is trying to resolve. If found an entry, read constructor available (This article is only aboue constructor Dependency injection) , if there is a defualt constructor, great. Call this default constructor using reflection and then you have concrete instance, store it in the local mapping of base type and instances, and return the instance. If no default contructor, get all parameters needed by the contructor, and do a resolve over the parameter types (recursion).

The code...

.. IOCImpl
private object CreateInstance(Type baseType)
{
//1. Get available constructors.
//2. if zero arg, just call it.
//3. if not, get expected parameters
//4. recursively get instance of each param, and add in list.
//5. List.toArray.
Type concreteType;
object instance = null;
if(_module.TryGetConcreteType(baseType,out concreteType))
{
var constructors =
concreteType.GetConstructors(BindingFlags.Public BindingFlags.NonPublic BindingFlags.Instance);
if (!_abstract2InstanceMap.TryGetValue(baseType, out instance))
{
if (constructors.Length != 0)
{
foreach (var constructorInfo in constructors)
{
if (constructorInfo.GetParameters().Length == 0)
{
instance = constructorInfo.Invoke(new object[0]);
break;
}
else
{
var constructorParam = new List
();
foreach (var parameter in constructorInfo.GetParameters())
{
var paramType = parameter.ParameterType;
var paramInstance = CreateInstance(paramType);
constructorParam.Add(paramInstance);
}
instance = constructorInfo.Invoke(constructorParam.ToArray());
}
}
}
_abstract2InstanceMap[baseType]= instance;
}
}
return instance;
}


No comments:

Post a Comment