注入条件绑定 [英] Ninject conditional binding

查看:76
本文介绍了注入条件绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在与Ninject一起在家里进行一个简单的测试台项目,只是想看看我能用它做什么.首先,我将为某些服务构建一个控制台运行程序,该运行程序接受各种参数并基于输入的内容,使用为流畅接口提供的相同方法来配置要运​​行的模型.

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.

作为一个示例,假设我有一个详细度开关/o. /o可以作为/o:quiet/o:normal/o:verbose传递.各种选项都是不言自明的.

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.

为满足该论点,我想附上ILogger的各种实现方式-quiet获得一个仅打印关键消息的安静记录器,normal获得一个普通的记录器,而verbose获取一个可以打印所有内容的健谈记录器.

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");

...等等.

我看不到如何做这样的事情;所有条件绑定似乎都取决于注射目标的状态.这有什么意义呢?当消费类必须精确地详细说明确定它被赋予哪种具体类型所需的所有条件时,它不会破坏整个依赖注入点吗?为什么我不能只告诉Ninject我想要什么并得到它?

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?

推荐答案

ctx参数只是上下文绑定-没什么好说的,您需要对此稍加注意(除非您需要与委托人签名兼容的签名).

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).

请记住,尽管 RRR模式疯了.

您需要使用IW(使用V2语法):

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

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

(其中_是可怜的人使用F#模式匹配语法忽略输入)

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

这篇关于注入条件绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆