当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - Bind a service to several times the same service provider with NInject

问题描述:

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>();

}

}

}

网友答案:

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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: