如果我有一个使用 IPerson 接口(interface)的 Human 和 Dog 类的实现,以及使用 IFood 接口(interface)的 HumanFood 和 DogFood 类的实现。如何在我的主要功能中从使用 HumanFood 切换到 DogFood 以及从 Human 切换到 Dog?
目前这种写法给我一个“有多个匹配绑定(bind)可用”的错误。
谢谢!
public class Bindings : NinjectModule
{
public override void Load()
{
this.Bind<IFood>().To<HumanFood>();
this.Bind<IFood>().To<DogFood>();
this.Bind<IPerson>().To<Human>();
this.Bind<IPerson>().To<Dog>();
}
}
static void Main(string[] args)
{
IKernel kernel = new StandardKernel();
kernel.Load(Assembly.GetExecutingAssembly());
IFood food = kernel.Get<IFood>();
IPerson person = kernel.Get<IPerson>();
person.BuyFood();
Console.ReadLine();
}
请您参考如下方法:
执行此操作的典型方法是使用命名绑定(bind):
this.Bind<IFood>().To<HumanFood>().Named("HumanFood");
或根据 WhenInjectedInto 确定要使用的绑定(bind):
this.Bind<IFood>().To<HumanFood>().WhenInjectedInto<Human>();
this.Bind<IFood>().To<DogFood>().WhenInjectedInto<Dog>();
但是,这两者都代表了代码味道。您可能需要重新考虑为什么要根据目标注入(inject)不同的实现,并可能改为注入(inject)工厂模式的实现。
可以在此处找到您可以执行的一些操作的便捷概述:
http://lukewickstead.wordpress.com/2013/02/09/howto-ninject-part-2-advanced-features/