我定义了以下接口(interface):
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>
但出现错误:
There is no implicit reference conversion from 'CustomerService1' to 'ICustomService<CustomObject>'
而不是像这样注册:
services.AddTransient<ICustomService<MyObject1>, CustomService1>();
services.AddTransient<ICustomService<MyObject2>, CustomService2>();
像上面那样注册时,我的 IEnumerable services
是空的:
public ThirdService(IEnumerable<ICustomService<CustomObject>> services)
{
}
如何注入(inject) ICustomService
的所有实现?进入ThirdService
?
我正在努力做到这一点 ThirdService
可以给一个ID,然后获取所有CustomObject
使用该 ID 使用 GetById
在所有服务上。
最佳答案
假设没有其他接口(interface)方法具有 T
类型的参数, 类型的可变属性 T
,或返回使用 T
的泛型类型的方法以非协变的方式,你可以使T
协变使用 out
:
public interface ICustomService<out T> where T : CustomObject
这将使您的注册尝试有效:
services.AddTransient<ICustomService<CustomObject>, CustomService1>();
services.AddTransient<ICustomService<CustomObject>, CustomService2>();
Covariance确保 CustomService1
和 CustomService2
可以安全地用来代替 ICustomService<CustomObject>
, 尽管他们都声明了 MyObject
的子类作为通用参数。
关于c# - 在 C# 中,如何使用泛型的基类将泛型接口(interface)的所有实例注入(inject)到单个构造函数中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71470836/