"多个绑定"调用错误,当ninject2.Get<&具体类GT;() [英] "Multiple bindings" error when calling ninject2.Get<ConcreteClass>()

查看:186
本文介绍了"多个绑定"调用错误,当ninject2.Get<&具体类GT;()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要做这样的事情:

ConcreteClass foo = ninject2.Get<ConcreteClass>(
    new ConstructorArgument("bar", "qux"));

ninject2.Bind<ConcreteClass>().ToConstant(foo);

...

ConcreteClass foo = ninject2.Get<ConcreteClass>(); // fail!

当我尝试,我得到的错误错误激活具体类。多个匹配的绑定是可用的。

When I try, I get the error Error activating ConcreteClass. More than one matching bindings are available.

这是怎么回事?

推荐答案

开箱即用,Ninject(ESP V2 - 在V1,它是默认为一个可选的设置)在内部生成具体的类本身隐含的绑定,使用默认的作用域(瞬态在V2) 。这些注册被添加到绑定列表,如果你想通过自己加入他们。

OOTB, Ninject (esp. v2 - in v1, it was an optional setting that defaulted to on) internally generates implicit bindings for concrete classes to themselves, with the default scoping (Transient in v2). These registrations get added into the Bindings list as if you'd added them yourself via.

Bind<ConcreteClass>().ToSelf(); // .InTransientScope(); -- But that would be implicit

如果你需要什么东西在不同的绑定,你注册一个绑定 ING它会自动绑定,使用您的自定义位一拉前:

If you need anything different in your binding, you register a Binding before it gets auto-bound, with Your customisation bit a la:

Bind<ConcreteClass>().ToSelf().<<Your Customisation Bit>>;

在这种情况下,你的补救方法是使用这样的:

In this case, your remedy is to use something like:

Bind<ConcreteClass>().ToSelf().InSingletonScope().WithConstructorArgument( "foo", "bar");



其中, InSingletonScope()将匹配当前的代码,它看起来像您只想实例之一。一般来说,覆盖在其他的答案,人们不应该对 InSingletonScope 必然抢到第一作为不得已的手段。

Where InSingletonScope() would match your current code in that it looks like you only ever want to instantiate one. In general, as covered in other answers, one shouldnt necessarily grab for InSingletonScope as a tool of first resort.

这篇关于&QUOT;多个绑定&QUOT;调用错误,当ninject2.Get&LT;&具体类GT;()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆