Ninject - Multiple Classes Using Single Interface (more than one matching bindings are available)

限于喜欢 提交于 2020-01-05 09:33:14

问题


If I have an implementation of Human and Dog class which uses the IPerson interface and HumanFood and DogFood class using the IFood interface. How can I switch from using HumanFood to DogFood and Human to Dog in my main function?

Currently the way this is written it is giving me a "more than one matching bindings are available" error.

Thanks!

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

回答1:


Typical ways to do this is to either use named binding:

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

Or to determine the binding to use based on WhenInjectedInto:

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

However, both of these represent a code smell. You may want to rethink why you're injecting varying implementations depending on the destination and perhaps inject an implementation of the factory pattern instead.

A handy overview of some of the stuff you can do can be found here:

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



来源:https://stackoverflow.com/questions/26854101/ninject-multiple-classes-using-single-interface-more-than-one-matching-bindin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!