使用 Ninject IOC 替换工厂
我在解析器中有一个工厂方法。本质上,当我加载令牌时,我会查找该令牌的处理程序,或者直接转到默认处理程序。我已将其实现为 switch
和 Dictionary
但两种方法都要求我将映射存储在处理程序类之外的其他位置。
我们正在使用 Ninject 进行 IOC,所以我意识到我也可以使用它,
kernel.Get<ITokenHandler>(tokenName);
但这并不能节省我在两个位置存储有关处理程序可以处理的令牌的信息。有没有办法可以装饰处理程序以便自动映射?
I've got a factory method inside a parser. Essentially as I load a token I look up the handler for that token, or drop through to the default handler. I've implemented this as a switch
and as a Dictionary<string,Type>
but both approaches require me to store the mapping somewhere else than the handler class.
We are using Ninject for IOC and so I've realized I can also do it using
kernel.Get<ITokenHandler>(tokenName);
but that doesn't save me storing the information on what token the handler can deal with in 2 locations. Is there a way I can decorate the handler so this gets mapped automatically?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果我正确地理解了你的问题,听起来你想检索一个命名绑定。您没有提到您正在使用的 Ninject 版本,但根据您的代码片段,我猜测您正在使用 Ninject 2.0。如果是这种情况,那么我认为这足以满足您在模块中的绑定:
您将尽可能多的具体类型绑定到同一接口并按名称区分它们,然后使用您在问题中指定的精确语法检索它们。
如果我遗漏了一些关键信息,请告诉我。
If I follow your question correctly, it sounds like you want to retrieve a named binding. You didn't mention what version of Ninject you are using, but based on your code snippet, I am guessing you are using Ninject 2.0. If that's the case then I would think this would suffice for your binding in your module:
You bind as many concrete types to the same interface and differentiate them by name, and then retrieve them using the precise syntax you've specified in your question.
If I am missing something key, let me know.
我使用的一种技术是
绑定
内容,这样您就可以要求在您希望某人选择某些内容时传递一个参数(在上下文中)。http://ninject.codeplex.com/wikipage?title 之间=Providers%20and%20the%20Activation%20Context 和 http://ninject .codeplex.com/wikipage?title=Contextual%20Binding 您应该能够以这样的方式绑定事物,您可以说
Only(When.Context...)
来使选拔工作?One technique I've used is to
Bind
stuff in such a way that you can require handing in of a parameter (in the context) at the point where you want someone to select something out.Between http://ninject.codeplex.com/wikipage?title=Providers%20and%20the%20Activation%20Context and http://ninject.codeplex.com/wikipage?title=Contextual%20Binding you should be able to Bind things in such a way that you can say
Only(When.Context...)
to make the selection work?