2

Ninject 似乎没有正确使用WhenInjectedInto约束,同时也使用Lazy<T>。检查以下示例。OnLandAttack和OnLandAttackLazy应该使用Samurai实例。但是 Lazy<T> 版本以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();
    }
}
4

0 回答 0