Ninject - How to dynamically select an implementation to bind to an interface

此生再无相见时 提交于 2019-12-12 15:05:27

问题


I'm currently using Ninject to create instances of 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 are going to have several implementations of IObjC. What options do I have for continuing fluid assignment of implementation to interface for IObjA/IObjB but allowing for configurable assignment for IObjC?

I found a related question on SO but I don't know if I can support both a fluid and a configurable approach simultaneously.

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

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

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

Also, I know other frameworks like Castle support XML configuration but I would like to continue using Ninject.


回答1:


1 - your bindings to IObjC have nothing to do with any other bindings. it doesn't matter where, when, or how you bind other services.

2 - you can use the XML extensions, but I would ask why you think you need it to be configurable.

3 - there are 2 possibilities for your conditional. first is that you want to make a decision at startup to determine whether to use ObjC1 for the entire lifetime of the app, or ObjC2. if that's the case, your code is ok. however, if you want to dynamically decided which object to use each time you resolve the binding, you will need to put the condition inside your binding, like so:

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

alternately, you can use Named bindings:

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

or "When" conditions to help:

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


来源:https://stackoverflow.com/questions/4606848/ninject-how-to-dynamically-select-an-implementation-to-bind-to-an-interface

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