Bind a service to several times the same service provider with NInject

52 Views Asked by At

I'd like to use multiple binding for multiple injection with NInject, just as the official documentation states, but using several times the same binding.

public class Samurai 
{
    readonly IWeapon[] allWeapons;
    public Samurai(IWeapon[] allWeapons) 
    {
        this.allWeapons = allWeapons;
    }

    public void Attack(string target) 
    {
        foreach (IWeapon weapon in this.allWeapons)
            Console.WriteLine(weapon.Hit(target));
    }
}

Then, instead of giving the Samurai a Sword and a Dagger as the official example, I want him to have a lot of Shuriken. Of course I can loop over the binding, but is there a better way to do that? Maybe define an extension method?

class TestModule : Ninject.Modules.NinjectModule
{
    public override void Load()
    {
        for (int i=0; i<100; i++)
        {
            Bind<IWeapon>().To<Shuriken>();
        }
    }
}
1

There are 1 best solutions below

0
On BEST ANSWER

I think a DI container is not a good fit to fulfill this requirement. If anything i would somewhere configure what type and how many IWeapon you want to instanciate and bind a provider for ICollection<IWeapon> which then can create these according to configuration.