Skip to content

Instantly share code, notes, and snippets.

@OzieWest
Created March 6, 2015 08:58
Show Gist options
  • Select an option

  • Save OzieWest/c65fd403f10b6c0f8a6e to your computer and use it in GitHub Desktop.

Select an option

Save OzieWest/c65fd403f10b6c0f8a6e to your computer and use it in GitHub Desktop.
Own IoC Container
public class MyContainer
{
private readonly Dictionary<Type, Type> _registrations;
public MyContainer()
{
_registrations = new Dictionary<Type, Type>();
}
public void Register<T, TS>()
{
_registrations.Add(typeof(T), typeof(TS));
}
public T Get<T>()
{
return (T)GetObject(typeof(T));
}
private object GetObject(Type parameterType)
{
if (!_registrations.ContainsKey(parameterType)) throw new Exception("Type not registered");
var concreteType = _registrations[parameterType];
var constructorParams = GetConstructorParams(concreteType);
return Activator.CreateInstance(concreteType, constructorParams.ToArray());
}
private IEnumerable<object> GetConstructorParams(Type concreteType)
{
var constructor = concreteType.GetConstructors().Single();
var cparams = constructor.GetParameters();
foreach (var parameterInfo in cparams)
{
yield return GetObject(parameterInfo.ParameterType);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment