我是Ninject的新手,在做了一些研究之后,我想出了一个例子:
public interface IWeapon
{
void Hit(Target target);
}
public class Sword : IWeapon
{
public void Hit(Target target)
{
//do something here
}
}
public class Character
{
private IWeapon weapon;
public Character(IWeapon weapon)
{
this.weapon = weapon;
}
public void Attack(Target target)
{
this.weapon.Hit(target);
}
}
public class Bindings : NinjectModule
{
public overrides void Load()
{
Bind<IWeapon>().To<Sword>();
}
}
public void Main()
{
Target sometarget = new Target();
Kernel kernel = new StandardKernel(new Bindings());
var weapon = kernel.Get<IWeapon>();
var character = new Character(weapon);
character.Attack(sometarget);
}
如您所见,为了解决依赖关系,我必须使用IWeapon
提取Kernel
的实例并将其传递给Character
的构造函数。我觉得这有些丑陋,我想知道有没有办法可以直接拉出Character
的实例,而Ninject会自动解决IWeapon
的依赖关系?类似的东西:
Character character = kernel.Resolve<Character>();
答案 0 :(得分:1)
你还没有注册角色。创建一个ICharacter接口并将其绑定到Character类。然后,当您尝试解析ICharacter时,Ninject将看到它需要一个IWeapon实例用于Character构造函数,它将获得一个注册到该接口的实例。
答案 1 :(得分:1)
默认情况下,Ninject允许您使用正确的绑定自动解析具体类型。在你的实例中,你可以这样做:
public void Main()
{
Target sometarget = new Target();
IKernel kernel = new StandardKernel(new Bindings());
//var weapon = kernel.Get<IWeapon>();
var character = kernel.Get<Character>();
character.Attack(sometarget);
}
有关更多信息,请阅读Ninject wiki:https://github.com/ninject/ninject/wiki/Dependency-Injection-With-Ninject