“Multiple bindings” error when calling ninject2.Get<ConcreteClass>()

ぐ巨炮叔叔 提交于 2019-12-08 04:18:20

问题


I'd like to do something like this:

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.

What is happening here?


回答1:


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

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");

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.



来源:https://stackoverflow.com/questions/3543565/multiple-bindings-error-when-calling-ninject2-getconcreteclass

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!