Search code examples
c#dependency-injectioninversion-of-controlninjectconstructor-injection

Ninject multi-injection is not as greedy as I would have thought! How come?


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?


Solution

  • That's a bug - GetAll will not return all instances in case conditional and unconditional bindings are mixed.

    It's fixed in version Version 2.4.0.0