0

使用 Ninject 重写以下示例会是什么样子?

具体来说,您如何将武士绑定到手里剑和剑上?

(来自https://github.com/ninject/ninject/wiki/Dependency-Injection-By-Hand

interface IWeapon
{
    void Hit(string target);
}

class Sword : IWeapon
{
    public void Hit(string target) 
    {
        Console.WriteLine("Chopped {0} clean in half", target);
    }
}

class Shuriken : IWeapon
{
    public void Hit(string target)
    {
        Console.WriteLine("Pierced {0}'s armor", target);
    }
}

class Program
{
    public static void Main() 
    {
        var warrior1 = new Samurai(new Shuriken());
        var warrior2 = new Samurai(new Sword());
        warrior1.Attack("the evildoers");
        warrior2.Attack("the evildoers");    
       /* Output...
        * Piereced the evildoers armor.
        * Chopped the evildoers clean in half.
        */
    }
}
4

1 回答 1

2

IWeapon您可以在先解决后简单地重新绑定Samurai

StandardKernel kernel = new StandardKernel();

kernel.Bind<IWeapon>().To<Sword>().Named();
Samurai samurai1 = kernel.Get<Samurai>();
samurai1.Attack("enemy");

kernel.Rebind<IWeapon>().To<Shuriken>();
Samurai samurai2 = kernel.Get<Samurai>();
samurai2.Attack("enemy");

或者,您可以使用命名绑定。首先需要重新定义Samurai的构造函数,Named在其依赖项中添加一个属性:

public Samurai([Named("Melee")]IWeapon weapon)
{
    this.weapon = weapon;
}

然后,您还需要为绑定命名:

StandardKernel kernel = new StandardKernel();

kernel.Bind<IWeapon>().To<Sword>().Named("Melee");
kernel.Bind<IWeapon>().To<Shuriken>().Named("Throwable");

Samurai samurai = kernel.Get<Samurai>();
samurai.Attack("enemy"); // will use Sword

确实有很多选择 - 我建议浏览@scottm 提供的链接并将它们全部检查出来。

于 2012-07-19T18:21:22.370 回答