使用 NInject 时,如果我为
IEnumerable<T>
设置了绑定,如果我直接请求 IEnumerable<T>
,它将起作用,但如果另一个绑定对象需要 IEnumerable<T>
,则不起作用。这是故意设计的吗?
class Program
{
static void Main(string[] args)
{
var k = new StandardKernel();
k.Bind<IEnumerable<int>>().ToMethod(GetInts);
k.Bind<IFoo>().To<Foo>(); // Has an IEnumerable<int> constructor arg
var works = k.Get<IEnumerable<int>>(); // returns the array of ints
var tst = k.Get<IFoo>(); // Empty integer array is passed in by ninject???
tst.Get(); // returns an empty integer array?
return;
}
public static int[] GetInts(IContext ctx)
{
return new int[] { 1, 2, 3, 4, 5 };
}
}
public interface IFoo
{
IEnumerable<int> Get();
}
public class Foo : IFoo
{
private int[] _vals;
public Foo(IEnumerable<int> vals)
{
_vals = vals.ToArray();
}
public IEnumerable<int> Get()
{
return _vals;
}
}
您正在看到多次注射发生。
您可以通过在绑定中添加显式 Get 来覆盖它:
k.Bind<IFoo>().To<Foo>()
.WithConstructorArgument( "vals", ctx=>ctx.Kernel.Get<IEnumerable<int>>());
(尽管如果您查看源代码,我相信您会找到一种抑制多次注入的方法。)