我有什么:
public interface IBla
{
}
public class Bla1 : IBla
{
}
public class Bla : IBla
{
}
public class Consumer
{
private readonly IBla[] _array;
public Consumer(IBla[] array)
{
_array = array;
}
}
public static class NinjectExtensions
{
public class BindListExpression<TElement>
{
private readonly IKernel _kernel;
private readonly List<Type> _types = new List<Type>();
public BindListExpression(IKernel kernel)
{
_kernel = kernel;
}
public BindListExpression<TElement> ImplementedBy<T>() where T : TElement
{
var type = typeof(T);
_kernel.Bind<T>().To(type);
_types.Add(type);
return this;
}
public void Bind()
{
Func<TElement[]> createObjects = () =>
{
var sourceArray = new TElement[_types.Count];
for (var i = 0; i < _types.Count; i++)
{
var value = _kernel.Get(_types[i]);
sourceArray[i] = (TElement)value;
}
return sourceArray;
};
_kernel.Bind<TElement[]>().ToMethod(x => createObjects().ToArray());
_kernel.Bind<List<TElement>>().ToMethod(x => (createObjects().ToList()));
_kernel.Bind<IEnumerable<TElement>>().ToMethod(x => createObjects().ToList());
}
}
public static BindListExpression<T> ListOf<T>(this IKernel kernel)
{
return new BindListExpression<T>(kernel);
}
}
用法:
// Binds items in the given order as a list (Ninject does not guarantee the given order so I use this mechanism).
kernel.ListOf<IBla>()
.ImplementedBy<Bla1>()
.ImplementedBy<Bla>()
.Bind();
var consumer = kernel.Get<Consumer>(); // result: consumer._array is empty?! --> what is imo wrong
var array = kernel.Get<IBla[]>(); // result: Bla1, Bla --> correct
为什么Ninject在使用
Get<IBla[]>()
和带有参数IBla[]
的构造函数时结果不同?