3

如果我有以下情况:

public MyClass(IServiceOne serviceOne, IServiceTwo serviceTwo, IServiceThree serviceThree = null)
{
  this.serviceOne = serviceOne;
  this.serviceTwo = serviceTwo;
  this.serviceThree = serviceThree ?? new ServiceThree("some-info");
}

如何告诉 Ninject 绑定前两个参数,而不是 IServiceThree 类型的参数?这甚至可能吗?

我希望 serviceThree 作为构造函数参数的原因是为了可测试性 - 我需要能够从我的测试中注入一个模拟。

4

3 回答 3

5

如果您不打算使用构造函数注入,那么您不妨将其从构造函数参数列表中删除,并按照您的操作方式手动初始化它。换句话说,只需传递两个参数而不是三个。

更新:你可以做的是注入null价值。据我记得,您必须执行以下操作:

_kernel.Settings.AllowNullInjection = true;

然后,您可以删除第三个参数的绑定(如果存在)。

于 2013-03-01T12:07:07.340 回答
0

为了可测试性,您需要模拟您希望表现为 null 的接口(在调用其方法时什么也不做)并作为构造函数参数传递。

您的做法是错误的,您将测试代码依赖项添加到生产代码中。

于 2016-10-06T20:05:07.117 回答
0

您可以通过如下配置绑定来避免AllowNullInjection全局设置,同时仅在绑定存在时才注入参数:

Kernel.Bind<IMyClass>()
      .To<MyClass>()
      .WithConstructorArgument(typeof(IServiceThree), c => c.Kernel.TryGet<IServiceThree>());
于 2019-12-03T14:55:16.517 回答