【问题标题】:Ninject - Multiple Classes Using Single Interface (more than one matching bindings are available)Ninject - 使用单个接口的多个类(有多个匹配的绑定可用)
【发布时间】:2015-01-07 08:45:23
【问题描述】:

如果我有一个使用 IPerson 接口的 Human 和 Dog 类的实现,以及使用 IFood 接口的 HumanFood 和 DogFood 类。如何在我的主要功能中从使用 HumanFood 切换到 DogFood 和 Human 切换到 Dog?

目前的编写方式是给我一个“多个匹配的绑定可用”错误。

谢谢!

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();
}

【问题讨论】:

    标签: c# inversion-of-control ninject-2


    【解决方案1】:

    执行此操作的典型方法是使用命名绑定:

    this.Bind<IFood>().To<HumanFood>().Named("HumanFood");
    

    或者根据WhenInjectedInto来确定要使用的绑定:

    this.Bind<IFood>().To<HumanFood>().WhenInjectedInto<Human>();
    this.Bind<IFood>().To<DogFood>().WhenInjectedInto<Dog>();
    

    但是,这两者都代表代码气味。您可能需要重新考虑为什么要根据目标注入不同的实现,并且可能要注入工厂模式的实现。

    您可以在这里找到一些您可以做的事情的方便概述:

    http://lukewickstead.wordpress.com/2013/02/09/howto-ninject-part-2-advanced-features/

    【讨论】:

      猜你喜欢
      • 2019-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多