Ninject多播 [英] Ninject Multicasting
问题描述
我要绑定一个服务的多种实现,并已全部叫一次:
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不喜欢这一点,将抛出关于有多个绑定例外。 ?有没有一种办法可以解决这个错误,并且都被称为实现
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?
此外,绑定<>
通话可以在可能会或可能不会在运行时加载不同的项目,所以创建一个单一的执行调用它们将无法正常工作。这是一个ASP.NET MVC 3网站插件架构的一部分。
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.
推荐答案
如果您使用构造器注入有一个列表与LT; IBreakfast>
参数,则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 call Eat
on these instances.
您可以使用此模式来获得Ninject创建列表你的插件实例。
You can use this pattern to get Ninject to create a list of your plugins for instance.
[Test]
public void Test()
{
IKernel kernel = new StandardKernel();
kernel.Bind<IBreakfast>().To<Eggs>();
kernel.Bind<IBreakfast>().To<Spam>();
kernel.Bind<IBreakfast>().To<MoreSpam>();
var bling = kernel.Get<Bling>();
}
private class Bling
{
public Bling(List<IBreakfast> things)
{
things.ForEach(t => t.Eat());
}
}
private interface IBreakfast
{
void Eat();
}
private class Ingrediant : IBreakfast
{
public void Eat(){Console.WriteLine(GetType().Name);}
}
private class Eggs : Ingrediant{}
private class Spam : Ingrediant{}
private class MoreSpam : Ingrediant { }
输出:
鸡蛋结果
垃圾邮件< BR>
MoreSpam
Eggs
Spam
MoreSpam
这篇关于Ninject多播的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!