Ninject组播
我想绑定一个服务的多个实现并同时调用所有这些实现:
var kernel = new StandardKernel();
kernel.Bind<IBreakfast>.To<Spam>();
kernel.Bind<IBreakfast>.To<Eggs>();
kernel.Bind<IBreakfast>.To<MoreSpam>();
kernel.Get<IBreakfast>().Eat(); // call Eat method on all three bound implementations
Ninject 不喜欢这样,并且会抛出有关多个绑定的异常。有没有办法可以解决该错误并调用所有实现?
此外,Bind<> 调用可以位于不同的项目中,这些项目可能会也可能不会在运行时加载,因此创建单个实现来调用它们是行不通的。这是 ASP.NET MVC 3 网站插件架构的一部分。
I want to bind multiple implementations of a service and have all of them called at once:
var kernel = new StandardKernel();
kernel.Bind<IBreakfast>.To<Spam>();
kernel.Bind<IBreakfast>.To<Eggs>();
kernel.Bind<IBreakfast>.To<MoreSpam>();
kernel.Get<IBreakfast>().Eat(); // call Eat method on all three bound implementations
Ninject doesn't like that, and will throw an exception about having multiple bindings. Is there a way I can get around that error, and have all the implementations called?
Also, the Bind<>
calls can be in different projects which may or may not be loaded at run-time, so creating a single implementation to call them won't work. This is part of a plug-in architecture for an ASP.NET MVC 3 web site.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您使用构造函数注入并具有
List
参数,则 Ninject 将使用您的所有绑定构造一个列表。然后,您可以在这些实例上调用Eat
。例如,您可以使用此模式让 Ninject 创建插件列表。
输出:
If you use constructor injection and have a
List<IBreakfast>
parameter, then Ninject will construct a list using all your bindings. You can then callEat
on these instances.You can use this pattern to get Ninject to create a list of your plugins for instance.
Output:
您不能将许多具体类绑定到一个接口,这违反了 DI 规则。
基本上您想要做的是初始化几个具体实例并调用它们的方法。
您可能想检查一下:
You can't bind many concrete classes to once single interface, that's against DI rules.
What basically you want to do is, initialize couple of concrete instances and call their method.
You may want to check this out: