Skip to content

Instantly share code, notes, and snippets.

@antonydenyer
Created January 23, 2013 17:35
Show Gist options
  • Save antonydenyer/4610697 to your computer and use it in GitHub Desktop.
Save antonydenyer/4610697 to your computer and use it in GitHub Desktop.
NinjectIocAdapter with IEnumerable Resolution Looking for better ways to do this
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