Ninject inject在创建集合时向集合添加元素

时间:2010-10-21 12:21:32

标签: c# dependency-injection ninject ninject-2

我正在使用MVVM灯并设置了如下绑定:

class TestModule:NinjectModule
{
    public override void Load()
    {
        Bind<ICollection<Element>>().To<Collection<Element>>();
        Bind<Element>().ToSelf();
    }
}

当我尝试获取ICollection时,我得到一个包含ONE元素的集合。我期待一个很好的收藏。

    var _kernel = new StandardKernel(new TestModule());

    var col = _kernel.Get<ICollection<Element>>();
    Console.WriteLine("Count={0}", col.Count);   //Write "Count=1", Expect "Count=0"

1 个答案:

答案 0 :(得分:5)

Ninject mailing list已回答这个问题。

此行为是预期的。注入集合时,它将找到所有绑定 与通用参数匹配并将它们添加到集合中 注射。如果删除Element上的绑定,则会收到空集合 被注射。

另一个example is given显示了基于此行为可以完成的任务。