[英]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.