using Ninject.Modules;
10 class WarriorModule : NinjectModule
11 {
12 override void Load()
13 {
14 Bind<IWeapon>().To<Sword>();
15 Bind<Samurai>().ToSelf();
创建模块(Module)后,将它们加载到Kernel容器中。调用Kernel的Get()方法,获取Ninject的类别实例。
class Program
static void Main(
string[] args)
14 IKernel kernal =
new StandardKernel(
new WarriorModule());
15 //Samurai s = new Samurai(kernal.Get<IWeapon>()); 构造函数注入16 Samurai s = kernal.Get<Samurai>();
17 s.Attack(
enemy");
18 19 Console.ReadKey();
20 }
21 }
22 }
如果需要的话,也可以创建多个模块(Module),将它们参数传递到Kernel的构造函数中。
class Module1 {
2 override void Load() { ... }
3 }
4 5 class Module2 {
6 7 }
8 9 class Program {
10 void Main()
11 {
12 IKernel kernel =
new Module1(),
new Module2(),...);
13 ...
14 }
以上代码附件:Ninject构造函数注入.rar
2>、Ninject属性依赖注入(Property Injection)
与构造函数注入不同,可以有多个属性(Property)声明[Inject] Attribute。
修改Samurai类和Program类,其他不变。
Samurai类注入属性:
17
18 /// 定义注入接口属性
19 /// 20 [Inject]
21 public IWeapon Weapon
22 {
23 get24 {
25 return _weapon;
26 }
27 set28 {
29 _weapon = value;
30 }
31 }
32 33 34 {
35 _weapon.Hit(target);
36 }
37 }
38 }
Program类调用:
using System.Text;
using Ninject;
namespace NInjectApp
{
class Program
{
string[] args)
{
IKernel kernal =
new WarriorModule());
Samurai s =
new Samurai() { Weapon = kernal.Get<IWeapon>() };
属性注入
s.Attack(
");
Console.ReadKey();
}
}
}
3>、Ninject方法注入(Method Injection)
Ninject可以有多个方法(Method)声明[Inject]属性(Attribute)。
Samurai类添加注入方法:
11
12 void Arm(IWeapon weapon)
Program类调用注入方法:
15 Samurai s =
new Samurai();
16 s.Arm(kernal.Get<IWeapon>());
方法注入 4>、Ninject字段注入(Field Injection)
Ninject可以有多个字段(Field)声明[Inject]属性(Attribute),但在实际应用中尽量避免使用字段注入。
Samurai类添加注入字段:
15 [Inject]
16 17 20 _weapon.Hit(target);
22 }
23 }
Program类中调用注入字段:
16 s._weapon = kernal.Get<IWeapon>();
需将Samurai类中字段_weapon修饰符改为public才可以访问
参考资料:
http://ninject.codeplex.com/wikipage?title=Injection%20Patterns&referringTitle=Dependency%20Injection%20With%20Ninject
(编辑:李大同)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!