Ninject 条件绑定
我正在家里用 Ninject 玩一个简单的测试台项目,只是想看看我能用它做什么。作为起点,我正在为某些服务构建一个控制台运行程序,它接受各种参数,并根据它所输入的内容,使用为流畅界面提供的相同方法来配置要运行的模型。
举个例子,假设我有一个详细程度开关,/o
。 /o
可以作为 /o:quiet
、/o:normal
或 /o:verbose
传递。各种选项都是不言自明的。
为了满足这个论点,我想附加 ILogger 的各种实现 - Quiet 获取仅打印关键消息的安静记录器,Normal 获取普通记录器,而 verbose 获取打印所有内容的聊天记录器。
我想做的是模块中的一些事情,例如:
Bind<ILogger>().To<QuietLogger>().When(VerbosityParameter=="quiet");
Bind<ILogger>().To<VerboseLogger>().When(VerbosityParameter=="verbose");
...等等。
我不知道如何做这样的事情;所有条件绑定似乎都取决于注入目标的状态。那有什么意义呢?当消费类必须准确详细地指定确定所给出的具体类型所需的所有条件时,它是否会破坏依赖注入的整个要点?为什么我不能直接告诉 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.
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
ctx
参数只是上下文绑定 - 没有什么说明您需要稍微注意它(除非您需要与委托签名兼容)。但请记住 RRR 模式,不要发疯。
IOW 你需要(在 V2 语法中这样做):(
其中
_
是一个穷人的洋泾浜使用 F# 模式匹配语法来忽略输入)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):
(Where
_
is a poor man's pidgin use of the F# pattern matching syntax for ignoring inputs)在这种特殊情况下,我不会替换记录器实例,而是配置您的日志记录框架以准确记录您想要的内容。
此外,
When
条件不依赖于目标,您可以在其中放置任何类型的条件。例如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.