现在的位置: 首页 > 综合 > 正文

多注入

2013年06月23日 ⁄ 综合 ⁄ 共 620字 ⁄ 字号 评论关闭

下面介绍一下如何在Ninject范围内多次注入。

现在,我们要给士兵装备多种武器,有剑有大刀。

修改Samuria类,修改后的代码如下:

 1 class Samurai
 2     {
 3         readonly IWeapon[] weapons;
 4         public Samurai(IWeapon[] weapons)
 5         {
 6             this.weapons = weapons;
 7         }
 8 
 9         public void Attack(string targer)
10         {
11             foreach (IWeapon weapon in weapons)
12             {
13                 weapon.Hit(targer);
14             }
15         }
16     }

在Ninject的Model类中绑定多个武器:

1 class TestModel:Ninject.Modules.NinjectModule
2     {
3         public override void Load()
4         {
5             Bind<IWeapon>().To<Sword>();
6             Bind<IWeapon>().To<Shuriken>();
7         }
8     }

然后在主函数中,开枪

1 static void Main(string[] args)
2         {
3             IKernel kernel = new StandardKernel(new TestModel());
4             var samurail = kernel.Get<Samurai>();
5             samurail.Attack("your army!");
6 
7             Console.Read();
8         }

这样就实现了给一个士兵绑定多把武器。

抱歉!评论已关闭.