我想绑定(bind)一个服务的多个实现,并同时调用它们:
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)的异常。有没有一种方法可以解决该错误并调用所有实现?
另外,Bind<>
调用可以在不同的项目中,这些项目可能会或可能不会在运行时加载,因此创建一个单一的实现来调用它们是行不通的。这是 ASP.NET MVC 3 网站插件架构的一部分。
最佳答案
如果你使用构造函数注入(inject)并且有一个 List<IBreakfast>
参数,然后 Ninject 将使用您的所有绑定(bind)构造一个列表。然后您可以调用 Eat
在这些情况下。
例如,您可以使用此模式让 Ninject 创建您的插件列表。
[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 { }
输出:
Eggs
Spam
MoreSpam
关于c# - Ninject 组播,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7959709/