Skip to content

Instantly share code, notes, and snippets.

@Foovanadil
Created August 5, 2014 23:43
Show Gist options
  • Save Foovanadil/f4e17b1655fbbf7484c0 to your computer and use it in GitHub Desktop.
Save Foovanadil/f4e17b1655fbbf7484c0 to your computer and use it in GitHub Desktop.
Open Generic IoC container
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