gpt4 book ai didi

c# - Ninject 如何在一次调用中解决依赖关系

转载 作者:行者123 更新时间:2023-12-02 04:31:06 25 4
gpt4 key购买 nike

我是 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);
}

如您所见,为了解决依赖性,我必须使用 Kernel 拉取 IWeapon 实例并将其传递给 Character的构造函数。我觉得这有点难看,我想知道有没有一种方法可以直接拉取 Character 实例,并且 Ninject 会自动解决与 IWeapon 的依赖关系?像这样的东西:

Character character = kernel.Resolve<Character>();

最佳答案

默认情况下,Ninject 将允许您使用正确的绑定(bind)自动解析具体类型。在您的实例中,您可以这样做:

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

关于c# - Ninject 如何在一次调用中解决依赖关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23100001/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com