public
Last active

WP7 IoC

  • Download Gist
IoC.cs
C#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
public static partial class IoC
{
private static readonly Dictionary<Type, Type> _registration = new Dictionary<Type, Type>();
private static readonly Dictionary<Type, object> _rot = new Dictionary<Type, object>();
private static readonly object[] _emptyArguments = new object[0];
private static readonly object _syncLock = new object();
 
static partial void RegisterAll();
 
static IoC()
{
RegisterAll();
}
 
public static object Resolve(Type type)
{
lock (_syncLock)
{
if (!_rot.ContainsKey(type))
{
if (!_registration.ContainsKey(type))
{
throw new Exception("Type not registered.");
}
var resolveTo = _registration[type] ?? type;
var constructorInfos = resolveTo.GetConstructors();
if (constructorInfos.Length > 1)
throw new Exception("Cannot resolve a type that has more than one constructor.");
var constructor = constructorInfos[0];
var parameterInfos = constructor.GetParameters();
if (parameterInfos.Length == 0)
{
_rot[type] = constructor.Invoke(_emptyArguments);
}
else
{
var parameters = new object[parameterInfos.Length];
foreach (var parameterInfo in parameterInfos)
{
parameters[parameterInfo.Position] = Resolve(parameterInfo.ParameterType);
}
_rot[type] = constructor.Invoke(parameters);
}
}
return _rot[type];
}
}
 
public static T Resolve<T>()
{
return (T) Resolve(typeof (T));
}
 
public static void Register<I, C>() where C:class, I
{
lock (_syncLock)
{
_registration.Add(typeof(I), typeof(C));
}
}
 
public static void Register<C>() where C:class
{
lock(_syncLock)
{
_registration.Add(typeof(C), null);
}
}
}
IoC_Registration.cs
C#
1 2 3 4 5 6 7 8
public static partial class IoC
{
static partial void RegisterAll()
{
Register<IMyInterface, IMyImplementation>();
Register<IMyComponent>();
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.