- Ninject官方网址为: 。
- 类的定义
private IWeapon _weapon;
//构造函数注入
[Inject]
public Samurai(IWeapon weapon)
{
_weapon = weapon;
}
//属性函数注入
[Inject]
public IWeapon Weapon
{
get
{
return _weapon;
}
set
{
_weapon = value;
}
}
//方法函数注入
[Inject]
public void Arm(IWeapon weapon)
{
_weapon = weapon;
}
//字段函数注入
[Inject]
private IWeapon _weapon;
public void Attack(string target)
{
_weapon.Hit(target);
}
- 添加绑定关系(可创建多个Module)public class WarriorModule : NinjectModule{ public override void Load(){ Bind<IWeapon>().To<Sword>();Bind<Samurai>().ToSelf();}}
- 构造函数依注入(只能在一个构造函数上使用Inject) IKernel kernal = new StandardKernel(new WarriorModule());//Samurai s = new Samurai(kernal.Get<IWeapon>()); // 构造函数注入Samurai s = kernal.Get<Samurai>();s.Attack("enemy");
- 属性注入IKernel kernal = new StandardKernel(new WarriorModule()); Samurai s = new Samurai() { Weapon = kernal.Get<IWeapon>() };// 属性注入 s.Attack("enemy");
- 方法注入IKernel kernal = new StandardKernel(new WarriorModule());Samurai s = new Samurai();s.Arm(kernal.Get<IWeapon>()); // 方法注入s.Attack("enemy");
- 字段注入 IKernel kernal =