如何使用ninject重写?

时间:2012-07-19 18:07:59

标签: c# dependency-injection ninject

以下示例将如何重写以使用Ninject?

具体来说,你如何将武士与Shuriken和Sword捆绑在一起?

(来自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.
        */
    }
}

1 个答案:

答案 0 :(得分: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提供的链接并全部检查。