使用 Ninject IOC 替换工厂

发布于 2024-08-18 03:03:36 字数 345 浏览 2 评论 0原文

我在解析器中有一个工厂方法。本质上,当我加载令牌时,我会查找该令牌的处理程序,或者直接转到默认处理程序。我已将其实现为 switchDictionary 但两种方法都要求我将映射存储在处理程序类之外的其他位置。

我们正在使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

傲性难收 2024-08-25 03:03:36

如果我正确地理解了你的问题,听起来你想检索一个命名绑定。您没有提到您正在使用的 Ninject 版本,但根据您的代码片段,我猜测您正在使用 Ninject 2.0。如果是这种情况,那么我认为这足以满足您在模块中的绑定:

Bind<ITokenHandler>().To<YourConcreteTypeHere>().Named(tokenName);

您将尽可能多的具体类型绑定到同一接口并按名称区分它们,然后使用您在问题中指定的精确语法检索它们。

如果我遗漏了一些关键信息,请告诉我。

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:

Bind<ITokenHandler>().To<YourConcreteTypeHere>().Named(tokenName);

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.

高跟鞋的旋律 2024-08-25 03:03:36

我使用的一种技术是绑定内容,这样您就可以要求在您希望某人选择某些内容时传递一个参数(在上下文中)。

http://ninject.codeplex.com/wikipage?title 之间=Providers%20and%20the%20Activation%20Contexthttp://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?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文