Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 595
David Lay Avatar asked Feb 15 '11 13:02

David Lay


1 Answers

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);
like image 174
onof Avatar answered Oct 27 '22 16:10

onof