2017-08-24 55 views
2

我想註冊在Ninject一個通用的接口,然後我想一些其他的接口是通用接口:Ninject:不能註冊的通用接口等諸多接口

public interface ISE<T> { } 

public class SE<T> : ISE<T> { } 

public interface IConcreteSE_A : ISE<SomeClass_A> { } 
public interface IConcreteSE_B : ISE<SomeClass_B> { } 
public interface IConcreteSE_C : ISE<SomeClass_C> { } 


kernel.Bind(typeof(ISE<>)).To(typeof(SE<>)); 
kernel.Bind<IConcreteSE_A>().To(typeof(SE<>)); 
kernel.Bind<IConcreteSE_B>().To(typeof(SE<>)); 
kernel.Bind<IConcreteSE_C>().To(typeof(SE<>)); 

,但我得到錯誤:給出的通用參數數量不等於通用類型定義參數的數量當我嘗試注入例如IConcreteSE_A到我的web api控制器。

如何解決?

回答

1

這是因爲在IConcreteSE_AISE<SomeClass_A>之間沒有隱含的參考轉換。換句話說,不能保證實現ISE<SomeClass_A>SE<SomeClass_A>實際上滿足IConcreteSE_A的實現。

你可以通過創建一個實現兩個接口然後綁定到這個接口的具體類來解決這個問題。

public class SE<T> : ISE<T> { } 
public class SomeClassA { } 
public class ConcreteSE_A : ISE<SomeClass_A>, IConcreteSE_A { } 

public interface IConcreteSE_A : ISE<SomeClass_A> { } 

kernel.Bind(typeof(ISE<>)).To(typeof(SE<>)); 
kernel.Bind<IConcreteSE_A>().To<ConcreteSE_A>();