Ninject问题与上下文绑定和Lazy <t> </t>

时间:2014-09-15 16:06:22

标签: ninject lazy-loading ninject-extensions contextual-binding

Ninject似乎没有正确使用 WhenInjectedInto contstraint,同时还使用 Lazy&lt; T&gt; 。请检查以下示例。 OnLandAttack OnLandAttackLazy 应各自使用 Samurai 实例。但是懒惰的&lt; T&gt;版本以 SpecialNinja 实例结束。我猜它是因为它实际上没有在构造函数中初始化?但我认为该类型仍应正确注册。我错过了什么吗?仅供参考,这是使用Ninject 3.2.2和Ninject.Extensions.Factory扩展3.2.1

class Program
{
    static void Main(string[] args)
    {
        var kernel = new StandardKernel();
        kernel.Load(new WarriorModule());

        var amphibious = kernel.Get<IAttack>("amphibious");
        amphibious.Execute();

        var onLand = kernel.Get<IAttack>("onLand");
        onLand.Execute();

        var onLandLazy = kernel.Get<IAttack>("onLandLazy");
        onLandLazy.Execute();

        Console.ReadKey();
    }
}

public class WarriorModule : NinjectModule
{
    public override void Load()
    {
        Bind<IWarrior>().To<Samurai>().WhenInjectedInto<OnLandAttack>();
        Bind<IWarrior>().To<Samurai>().WhenInjectedInto<OnLandAttackLazy>();
        Bind<IWarrior>().To<SpecialNinja>(); // <-- for everything else

        Bind<IAttack>().To<AmphibiousAttack>().Named("amphibious");
        Bind<IAttack>().To<OnLandAttack>().Named("onLand");
        Bind<IAttack>().To<OnLandAttackLazy>().Named("onLandLazy");
    }
}


public interface IWarrior
{
    void Attack();
}

public class Samurai : IWarrior
{
    public void Attack()
    {
        Console.WriteLine("\tSamurai Attack");
    }
}

public class SpecialNinja : IWarrior
{
    public void Attack()
    {
        Console.WriteLine("\tSpecial Ninja Attack");
    }
}

public interface IAttack
{
    void Execute();
}

public class OnLandAttack : IAttack
{
    private readonly IWarrior warrior;

    public OnLandAttack(IWarrior warrior)
    {
        this.warrior = warrior;
    }

    public void Execute()
    {
        Console.WriteLine("Begin OnLand attack");
        this.warrior.Attack();
    }
}

public class OnLandAttackLazy : IAttack
{
    private readonly Lazy<IWarrior> warrior;

    public OnLandAttackLazy(Lazy<IWarrior> warrior)
    {
        this.warrior = warrior;
    }

    public void Execute()
    {
        Console.WriteLine("Begin OnLandLazy attack");
        this.warrior.Value.Attack();
    }
}

public class AmphibiousAttack : IAttack
{
    private readonly IWarrior warrior;

    public AmphibiousAttack(IWarrior warrior)
    {
        this.warrior = warrior;
    }

    public void Execute()
    {
        Console.WriteLine("Begin Amphibious attack");
        this.warrior.Attack();
    }
}

0 个答案:

没有答案