当我创建集合时,Ninject 注入将元素添加到集合中

发布于 2024-09-28 14:36:56 字数 557 浏览 0 评论 0原文

我正在使用 MVVM light 并按如下方式设置绑定:

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"

I'm using MVVM light and have set up the binding as following:

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

When I try to get a ICollection I get a collection with ONE element. I expect an exmpty collection.

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

醉酒的小男人 2024-10-05 14:36:56

Ninject 邮件列表 对此问题进行了解答。

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

另一个示例展示了可以根据此行为执行哪些操作。

This is answered on the Ninject mailing list.

This behavior is expected. When a collection is injected, it will find all bindings
that match the generic parameter and add them to the collection being
injected. If you remove your binding on Element, an empty collection would
be injected.

Another example is given showing what can be done based on this behavior.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文