MockingKernel命名多绑定作为构造函数参数

时间:2018-12-07 10:16:24

标签: c# .net dependency-injection ninject ninject-mockingkernel

所以说我有两个实现的接口

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";
    }
}

我有一个接受SwordDagger的对象。我使用docs中所述的Named多重绑定。

public class Samurai: ISamurai
{
    private readonly IWeapon sword;
    private readonly IWeapon dagger;

    public Samurai(
        [Named(nameof(Sword))] IWeapon sword,
        [Named(nameof(Dagger))] IWeapon dagger)
    {
        this.sword = sword;
        this.dagger = dagger;
    }
}

当在运行时情况下将其与常规绑定一起使用时,这可以很好地工作:

DependencyInjector.Kernel.Bind<IWeapon>().To<Sword>().Named(nameof(Sword));
DependencyInjector.Kernel.Bind<IWeapon>().To<Dagger>().Named(nameof(Dagger));

当我使用模拟内核时,这不起作用:

Mock<IWeapon> mockSword = new Mock<IWeapon>();
Mock<IWeapon> mockDagger = new Mock<IWeapon>();

MockingKernel.Rebind<IWeapon>().ToConstant(mockSword.Object).Named(nameof(Sword));
MockingKernel.Rebind<IWeapon>().ToConstant(mockDagger.Object).Named(nameof(Dagger));

MockingKernel.Get<Samurai>();

我收到以下类型的错误:

Message: OneTimeSetUp: Ninject.ActivationException : Error activating 
IWeapon
No matching bindings are available, and the type is not self-bindable.
Activation path:
  2) Injection of dependency IWeapon into parameter             
sword of constructor of type ISamurai
  1) Request for ISamurai

1 个答案:

答案 0 :(得分:1)

Rebind<IWeapon>()方法存在的问题是,即使您稍后指定IWeapon语法,它也会基于Named删除所有绑定。这意味着第二个重新绑定呼叫消除了第一个。因此,请尝试以下操作:

MockingKernel.Rebind<IWeapon>().ToConstant(mockSword.Object).Named(nameof(Sword));
MockingKernel.Bind<IWeapon>().ToConstant(mockDagger.Object).Named(nameof(Dagger));