How to conditionally bind an instance depending on the type entered using unity?

I'm used to Ninject, and for a specific project, I’m invited to learn Unity.

There is one thing, I can not find information on how to do this.

In Ninject, I can specify:

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 someone asks for a warrior named samurai, the samurai comes with a canana, and the ninja comes with a shuriken. As it should be.

I do not want to refer to the container of warriors to get the appropriate weapons, and I do not want to pollute the model with attributes (located in another assembly that does not have a reference to ninject or unity)

PD: I'm looking for a way to code, not through the xml configuration.

+6
ioc-container unity-container ninject
source share
1 answer

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); 
+7
source share

All Articles