Ninject conditional binding

↘锁芯ラ 提交于 2019-12-10 07:59:50

问题


I'm playing around with Ninject for a simple test-bed project at home, just to see what I can do with it. As a starting point I'm building a console runner for some service, which accepts a variety of arguments and based on what it gets in, uses the same methods provided for a fluent interface to configure a model to run.

As an example, suppose I have a verbosity switch, /o. /o can be passed as /o:quiet, /o:normal, or /o:verbose. The various options are self-explanatory.

To satisfy this argument I would like to attach various implementations of ILogger - quiet gets a quiet logger that prints only critical messages, normal gets a normal logger, and verbose gets a chatty logger that prints everything.

What I'd like to do is something in a module like:

Bind<ILogger>().To<QuietLogger>().When(VerbosityParameter=="quiet");
Bind<ILogger>().To<VerboseLogger>().When(VerbosityParameter=="verbose");

...and so on.

I can't see how to do anything like this; all the conditional bindings seem to be dependent on the state of the injection target. What's the point of that? Doesn't it defeat the entire point of dependency injection when the consuming class has to specify in exact detail all the conditions needed to determine what concrete type it gets given? Why can't I just tell Ninject what I want, and get it?


回答1:


The ctx parameter is just one input into the contextual binding - there's nothing saying you need to pay the slightest bit of attention to it (except you need to be signature compatible with the delegate signature).

Bear in mind the RRR pattern though and don't go crazy.

IOW you need to be (in V2 syntax doing it):

Bind<IWarrior>().To<Samurai>().When(_ => expression not involving context at all);

(Where _ is a poor man's pidgin use of the F# pattern matching syntax for ignoring inputs)




回答2:


In this special case I wouldn't replace the logger instance but rather configure your logging framework to log exactly what you want to.

Also the When condition does not depend on the target you can put there any kind of condition. E.g.

When(ctx => Configuration.Get("VerborsityLevel") == "quiet")


来源:https://stackoverflow.com/questions/8391521/ninject-conditional-binding

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