c# - 在 C# 中,如何使用泛型的基类将泛型接口(interface)的所有实例注入(inject)到单个构造函数中?

标签 c# .net generics dependency-injection interface

我定义了以下接口(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确保 CustomService1CustomService2可以安全地用来代替 ICustomService<CustomObject> , 尽管他们都声明了 MyObject 的子类作为通用参数。

关于c# - 在 C# 中,如何使用泛型的基类将泛型接口(interface)的所有实例注入(inject)到单个构造函数中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71470836/

相关文章:

c# - 套接字异常 : ErrorCode vs. 套接字错误代码

c# - 显式转换 XAttribute 值

java - 静态函数调用之前的泛型尖括号

c# - 如何模拟自定义 ValueResolver 构造函数参数

c# - 如何为User32.dll的sendInput方法在mouse_input中设置适当的缩放值?

asp.net - 识别唯一的浏览器/选项卡实例,例如用户在 mysite.com 上打开了 2 个选项卡 - 分别识别

c# - 在 Image-Box 中绘制星星

java - 将数据添加到java中的通用集合

java - 具有泛型的订阅模型 - 实现多个泛型接口(interface)

c# - 将 JSON 结构解析为对象,但该结构可能包含不同的名称