Created
August 5, 2014 23:43
-
-
Save Foovanadil/f4e17b1655fbbf7484c0 to your computer and use it in GitHub Desktop.
Open Generic IoC container
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Container | |
{ | |
Dictionary<Type,Type> interfaceToConcreteTypeMappings = new Dictionary<Type,Type>(); | |
public static Container Instance = new Container(); | |
private Container () | |
{ } | |
public void Register(Type interfaceType,Type concreteType) | |
{ | |
if (interfaceToConcreteTypeMappings.ContainsKey(interfaceType)) | |
{ | |
//Replace | |
interfaceToConcreteTypeMappings[interfaceType] = concreteType; | |
} | |
else | |
{ | |
interfaceToConcreteTypeMappings.Add(interfaceType,concreteType); | |
} | |
} | |
public T Resolve<T>() | |
where T: class | |
{ | |
Type tType = typeof(T); | |
if (!interfaceToConcreteTypeMappings.ContainsKey(tType)) | |
{ | |
try | |
{ | |
//If T is Generic find the Open Generic Type and see if that is registed | |
var genericType = tType.GetGenericTypeDefinition(); | |
var concreteClosedGenericType = interfaceToConcreteTypeMappings[genericType]; | |
var result = concreteClosedGenericType.MakeGenericType(typeof(T).GenericTypeArguments); | |
return Activator.CreateInstance(result) as T; | |
} | |
catch(Exception e) | |
{ | |
string message = e.Message; | |
} | |
return default(T); | |
} else | |
{ | |
return Activator.CreateInstance(interfaceToConcreteTypeMappings[tType]) as T; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment