使用 NInject,在注入 ctor arg 时解析 IEnumerable<T> 失败,但在执行 Get<IEnumerable<T>>()

问题描述 投票:0回答:1

使用 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;
    }
}
c# dependency-injection ninject
1个回答
4
投票

您正在看到多次注射发生。

您可以通过在绑定中添加显式 Get 来覆盖它:

k.Bind<IFoo>().To<Foo>()
    .WithConstructorArgument( "vals", ctx=>ctx.Kernel.Get<IEnumerable<int>>());

(尽管如果您查看源代码,我相信您会找到一种抑制多次注入的方法。)

© www.soinside.com 2019 - 2024. All rights reserved.