How to conditionally bind a instance depending on the injected type using unity?

后端 未结 1 1876
小鲜肉
小鲜肉 2021-01-12 18:35

I\'m used to Ninject, and for a specific project I\'m asked to learn Unity.

There is one thing i can\'t find information on how to do.

In Ninject I can state

相关标签:
1条回答
  • 2021-01-12 18:49

    This should work with Unity:

    Container
     .Register<IWeapon, Katana>("Katana")
     .Register<IWeapon, Shuriken>("Shuriken")
     .Register<IWarrior, Samurai>("Samurai", new InjectionConstructor(new ResolvedParameter<IWeapon>("Katana"))
     .Register<IWarrior, Ninja>("Ninja", new InjectionConstructor(new ResolvedParameter<IWeapon>("Shuriken")));
    

    Test:

    var samurai = Container.Resolve<IWarrior>("Samurai");
    Assert.IsTrue(samurai is Samurai);
    Assert.IsTrue(samurai.Weapon is Katana);
    
    var ninja = Container.Resolve<IWarrior>("Ninja");
    Assert.IsTrue(ninja is Ninja);
    Assert.IsTrue(ninja.Weapon is Shuriken);
    
    0 讨论(0)
提交回复
热议问题