Ninject - How to dynamically select an implementation for binding to an interface

I am currently using Ninject to instantiate interfaces in a WCF services application.

Bind<IObjA>().To<ObjA>().InRequestScope();
Bind<IObjB>().To<ObjB>().InRequestScope();
Bind<IObjC>().To<ObjC>().InRequestScope();

It works great, but we will have several IObjC implementations. What parameters do I have to continue assigning the implementation fluid for the interface for IObjA / IObjB, but with the possibility of a configurable assignment for IObjC?

I found a question related to SO , but I don't know if I can support both a fluid and custom approach at the same time.

For example, is it possible to use Ninject.extensions.xml for IObjC while continuing to use the above approach for IObjA and IObjB?

Is it advisable to have a conditional assignment for IObjC? It seems dirty, but at the same time it seems very simple.

if (condition1)
  Bind<IObjC>().To<ObjC1>().InRequestScope();
else if (condition 2)
  Bind<IObjC>().To<ObjC2>().InRequestScope();

, , XML Castle, Ninject.

+3
1

1 - IObjC . , , .

2 - XML, , , .

3 - . -, , , ObjC1 ObjC2. , . , , , , :

Bind<IObjC>().ToMethod( ctx => condition ? ctx.Kernel.Get<ObjC1>() : ctx.Kernel.Get<ObjC2>() );

, :

Bind<ILog>().ToConstant( LogManager.GetLogger( "Accounting" ) ).Named( "Accounting" );

"", :

Bind<ILog>().ToConstant( LogManager.GetLogger( "Background" ) ).When( context => context.Target != null && context.Target.Name == "backgroundLogger" );
+5

Source: https://habr.com/ru/post/1783679/


All Articles