Ninject Multiple Injection Interface Binding

I have the following classes:

using System; interface IA { } class A1 : IA { } class A2 : IA { } class B { public B(IA a) {} } class BProvider : Provider<B> { IA _a; public BProvider(IA a) { _a=a; } protected override B CreateInstance(IContext context) { return new B(_a); } } 

Ninject Load () module:

 Bind<IA>().To<A1>(); Bind<IA>().To<A2>(); Bind<B>().ToProvider<BProvider>(); 

Main code:

 kernel.GetAll<IA>(); // works fine kernel.GetAll<B>(); // I expect to get IEnumerable<B> with two elements, but instead of this I get an error that there are multiple bindings of IA and ninject cannot determine which to use 

So the question is, is it possible to make the last expression work as expected, or do it differently?

+7
source share
1 answer

He will throw this exception because Ninject will have to instantiate an object of type BProvider . To do this, he must fill out the IA dependency. But the moment ... are there two bindings on IA that I have to choose? ....

You can use some conditional binding to decide which implementation should be used. One way: NamedAttribute :

 Bind<IA>().To<A1>(); Bind<IA>().To<A2>().Named("SecondImpl"); Bind<B>().ToProvider<BProvider>(); class BProvider : Provider<B> { IA _a; public BProvider([Named("SecondImpl")]IA a) { _a=a; } protected override B CreateInstance(IContext context) { return new B(_a); } } 

In this case, A1 will be entered by default if the NamedAttribute not specified.

or as @Remo Gloor explains in this post: Configuring Ninject

 Bind<IA>().To<A1>(); Bind<IA>().To<A2>().WhenParentNamed("NeedSecondImpl"); Bind<B>().ToProvider<BProvider>().Named("NeedSecondImpl"); 

This is a bit cleaner because you don’t need to bind the code to Ninject and just allow it to be configured (in one place).

+2
source

All Articles