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

删除回忆录丶 提交于 2019-12-01 02:25:58

问题


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:

Bind<IWarrior>().To<Samurai>().Named("Samurai");
Bind<IWarrior>().To<Ninja>().Named("Ninja");
Bind<IWeapon>().To<Katana>().WhenInjectedInto(typeof(Samurai));
Bind<IWeapon>().To<Shuriken>().WhenInjectedInto(typeof(Ninja));

And then when one asks for the warrior named samurai, the samurai comes with kanana and the ninja comes with shurikens. As it should.

I don't want to reference the container in the warriors to get the appropriate weapon, and don't want to contaminate the model with attributes (is in another assembly that doesn't have reference to ninject or unity)

PD: I'm looking for a code way, not via xml config.


回答1:


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


来源:https://stackoverflow.com/questions/5004306/how-to-conditionally-bind-a-instance-depending-on-the-injected-type-using-unity

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