Multi injection

Ninject 允許注入多個對象到一個特殊的類型或者接口。例如,我們有一個接口 IWeapon,和兩個實現 Sword 和 Dagger :

public interface IWeapon
{
    string Hit(string target);
}

public class Sword : IWeapon 
{
    public string Hit(string target) 
    {
        return "Slice " + target + " in half";
    }
}

public class Dagger : IWeapon 
{
    public string Hit(string target) 
    {
        return "Stab " + target + " to death";
    }
}

如下的 Samurai 類,它的構造函數有一個IWeapon類型的數組,這意味着在構造過程中Ninject將與該類型相關的對象賦值給這個數組。

public class Samurai 
{
    readonly IWeapon[] allWeapons;

    public Samurai(IWeapon[] allWeapons) 
    {
        this.allWeapons = allWeapons;
    }

    public void Attack(string target) 
    {
        foreach (IWeapon weapon in this.allWeapons)
            Console.WriteLine(weapon.Hit(target));
    }
}

我們可以構造從IWeapon到 Sword 和 Dagger 類型的綁定:

class TestModule : Ninject.Modules.NinjectModule
{
    public override void Load()
    {
        Bind<IWeapon>().To<Sword>();
        Bind<IWeapon>().To<Dagger>();
    }
}

最終,核心會創建一個根據以上配置的模型。我們通過Ninject創建一個 Samurai 對象實例,當調用對象的Attack方法,我們會發現,所有的類型對象被綁定到了IWeapon數組。

class Program
{
    public static void Main() 
    {
        Ninject.IKernel kernel = new StandardKernel(new TestModule());

        var samurai = kernel.Get<Samurai>();
        samurai.Attack("your enemy");
    }
}

結果是:

Stab your enemy to death
Slice your enemy in half

內核也提供了一個GetAll方法用於獲得同樣的輸出:

class Program
{
    public static void Main() 
    {
        Ninject.IKernel kernel = new StandardKernel(new TestModule());

        IEnumerable<IWeapon> weapons = kernel.GetAll<IWeapon>();
        foreach(var weapon in weapons)
            Console.WriteLine(weapon.Hit("the evildoers"));
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章