Created
January 23, 2013 17:35
-
-
Save antonydenyer/4610697 to your computer and use it in GitHub Desktop.
NinjectIocAdapter with IEnumerable Resolution
Looking for better ways to do this
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 NinjectIocAdapter : IContainerAdapter | |
{ | |
private readonly IKernel _kernel; | |
public NinjectIocAdapter(IKernel kernel) | |
{ | |
_kernel = kernel; | |
} | |
public T TryResolve<T>() | |
{ | |
return _kernel.TryGet<T>(); | |
} | |
public T Resolve<T>() | |
{ | |
if (typeof (Array).IsAssignableFrom(typeof (T))) | |
{ | |
throw new NotSupportedException("Can not resolve array types, use IEnumerable") | |
} | |
if (typeof(T).IsGenericType && typeof(T).GetGenericTypeDefinition() == typeof(IEnumerable<>)) | |
{ | |
var elementType = typeof(T).GetGenericArguments()[0]; | |
var listOfTypes = Activator.CreateInstance(typeof(List<>).MakeGenericType(elementType)) as IList; | |
foreach (var o in _kernel.GetAll(elementType)) | |
{ | |
listOfTypes.Add(o); | |
} | |
return (T)listOfTypes; | |
} | |
return _kernel.Get<T>(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment