If I have a class with a ctor set up for multi-injection like this:
public Shogun(IEnumerable<IWeapon> allWeapons)
{
this.allWeapons = allWeapons;
}
And bindings set up like this:
Bind<IWeapon>().To<Sword>();
Bind<IWeapon>().To<Dagger>().WhenInjectedInto<Shogun>();
Then I would expect Shogun to be constructed with both weapons injected? But this isn't the case - it only gets the Dagger.
If I add a further binding like this:
Bind<IWeapon>().To<Sword>();
Bind<IWeapon>().To<Dagger>().WhenInjectedInto<Shogun>();
Bind<IWeapon>().To<Shuriken>().WhenInjectedInto<Shogun>();
Then Shogun gets the Dagger and the Shuriken. WhenInjectedInto<T>()
looks like it should only be constraining the binding it is applied to and not affecting other bindings. I find this behaviour very misleading.
Can someone explain what is happening here?
IWeapon
to be bound toSword
. Why should bindingIWeapon
toDagger
in the specific case prevent the general binding? This means I can write code that makes a specific binding and break more general bindings made elsewhere. It seems dangerous and counter-intuitive. – MillwrightWhenInjectedInto
, wouldn't it? I am new to ninject, but as far as I understand, the purpose of this feature is to have specific cases, as you have mentioned, handled. You wantIWeapon
to be bound toSword
in general; however, when injected intoShogun
, you want it to be bound toDagger
. If you wantShogun
to have bothSword
andDagger
injected,WhenInjectedInto
shouldn't be used, IMHO. – DavinDagger
orSword
) rather than the contract (i.e.IWeapon
), rather than saying "When injecting IWeapon into Shogun inject a Dagger". Read this way it makes sense. – MillwrightBind<IWeapon>().To<BoStaff>().When(x => true);
This doesn't mentionShogun
at all yet still turns up in the multi-injection whenSword
does not. – Millwright