我定義了以下介面:
public interface ICustomService<T> where T : CustomObject
{
IEnumerable<T> GetById(int Id);
...
}
以及它的 2 個實作,其中MyObject1&MyObject2都繼承自CustomObject
public class CustomService1 : ICustomService<MyObject1>
{
public IEnumerable<MyObject1> GetById(int Id)
{
...
}
}
public class CustomService2 : ICustomService<MyObject2>
{
public IEnumerable<MyObject2> GetById(int Id)
{
...
}
}
我嘗試將這兩個注冊為ICustomService<CustomObject>但得到錯誤:
沒有從“CustomerService1”到“ICustomService<CustomObject>”的隱式參考轉換
而是像這樣注冊:
services.AddTransient<ICustomService<MyObject1>, CustomService1>();
services.AddTransient<ICustomService<MyObject2>, CustomService2>();
像上面這樣注冊時,我的 IEnumerableservices是空的:
public ThirdService(IEnumerable<ICustomService<CustomObject>> services)
{
}
如何將所有實作注入ICustomServiceinto ThirdService?
我正在嘗試這樣做,以便ThirdService可以給定一個 ID,然后在所有服務上CustomObject使用該 ID獲取所有GetById內容。
uj5u.com熱心網友回復:
假設沒有其他介面方法具有型別引數、型別T可變屬性或回傳以非協變方式T使用的泛型型別的方法,則可以使用以下方法使該協變:TTout
public interface ICustomService<out T> where T : CustomObject
這將使您的注冊嘗試有效:
services.AddTransient<ICustomService<MyObject>, CustomService1>();
services.AddTransient<ICustomService<MyObject>, CustomService2>();
協方差確保CustomService1并且CustomService2可以安全地用于代替 a ICustomService<MyObject>,盡管它們都將 的子類宣告MyObject為泛型引數。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/443585.html
上一篇:從View獲取值到另一個控制器
