我正在研究 Ninject 作为新的我有一个来自“战士模块”类下面的代码的问题我们已经绑定了类的接口,但是为什么我们使用 .ToSelf() 和类 SWORD 我已经完成了谷歌,但我无法得到确切的逻辑在这背后..如果我删除这条线怎么办
Bind<Sword>().ToSelf();
Run Code Online (Sandbox Code Playgroud)
下面的代码
//interface
interface IWeapon
{
void Hit(string target);
}
//sword class
class Sword : IWeapon
{
public void Hit(string target)
{
Console.WriteLine("Killed {0} using Sword", target);
}
}
class Soldier
{
private IWeapon _weapon;
[Inject]
public Soldier(IWeapon weapon)
{
_weapon = weapon;
}
public void Attack(string target)
{
_weapon.Hit(target);
}
}
class WarriorModule : NinjectModule
{
public override void Load()
{
Bind<IWeapon>().To<Sword>();
Bind<Sword>().ToSelf();//why we use .Toself() with self
}
}
static void …Run Code Online (Sandbox Code Playgroud) c# asp.net-mvc dependency-injection ninject inversion-of-control