Bind multiple implementations to the same interface with ninject

烂漫一生 提交于 2019-12-04 22:34:03

The binding to multiple interfaces is fine. Ninject allows this. see here: https://github.com/ninject/Ninject/wiki/Multi-injection

The problem is that Ninject can not just magically give you the "one" that you want depending on constructor arguments. What Ninject is designed to do with the code you wrote is to give you ALL of the bindings at once, when you ask for a List.

So like others said, if you only want a single instance, it sounds like what you want is contextual bindings. However, the way you asked your question and the other answers are a bit confusing, because it makes it sound like multi-injection is not possible, but it is possible, if it is really what you want. (which in this case it isn't)

You need to tell ninject how it should know which binding to choose.

Have a look at conditional binding: https://github.com/ninject/ninject/wiki/Contextual-Binding

I would recommend using the .When(...) syntax but maybe you prefer using .Named(...) (i.E. assigning a name/identifier to every binding and passing that name to ninject in the .Get<IPresenter>("SomeName") call).

You need to use contextual bindings. I usually use the concrete "target" class to decide which service implementation the kernel will provide by using .WhenInjectedInto() or .WhenInjectecExactlyInto().

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