繁体   English   中英

我如何告诉 Ninject 不要注入我的构造函数参数之一?

[英]How do I tell Ninject not to inject one of my constructor parameters?

如果我有以下几点:

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 作为构造函数参数的原因是为了可测试性 - 我需要能够从我的测试中注入一个模拟。

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

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

_kernel.Settings.AllowNullInjection = true;

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

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

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

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

Kernel.Bind<IMyClass>()
      .To<MyClass>()
      .WithConstructorArgument(typeof(IServiceThree), c => c.Kernel.TryGet<IServiceThree>());

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM