我有什么:
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);
}
}
Usage:
// 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[]
?
通过构造函数注入,ninject 会翻译 ctor 参数IBla[]
to a IResolutionRoot.GetAll<IBla>().ToArray()
。这就是对多次注入的支持的实现方式。因此,ctor 请求不可能导致IResolutionRoot.Get<IBla[]>()
- 但这仍然是您可以手动完成的事情。
对于 ninject 转换为多重注入的所有集合类型都是如此(AFAIR 数组、IList
, IEnumerable
, 但不是ICollection
).
我建议使用另一个集合接口(例如ICollection
) 或集合实现作为构造函数参数。这将导致 ctor 注入和IResolutionRoot.Get
calls.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)