我定义了以下接口:

public interface ICustomService<T> where T : CustomObject
{
   IEnumerable<T> GetById(int Id);
   ...
}

和2个it实现,其中MyObject1&amp;MyObject2都是从CustomObject继承来的

public class CustomService1 : ICustomService<MyObject1>
{
    public IEnumerable<MyObject1> GetById(int Id)
    {
        ...
    }
}
public class CustomService2 : ICustomService<MyObject2>
{
    public IEnumerable<MyObject2> GetById(int Id)
    {
        ...
    }
}

我try 将这两个都注册为ICustomService<CustomObject>,但出现了错误:

没有从"CustomerService 1"到"ICCustomService"的隐式引用转换&lt;CustomObject&gt;'

而是这样注册:

services.AddTransient<ICustomService<MyObject1>, CustomService1>();
services.AddTransient<ICustomService<MyObject2>, CustomService2>();

当像上面那样注册时,我的IEnumerable services是空的:

public ThirdService(IEnumerable<ICustomService<CustomObject>> services)
{
    
}

如何将ICustomService的所有实现注入ThirdService

我正在try 这样做,以便ThirdService可以得到一个ID,然后在所有服务上使用GetById获取所有CustomObject个ID.

推荐答案

假设没有其他接口方法具有类型T的参数、类型T的可变属性,或返回以非协变方式使用T的泛型类型的方法,则可以使用out使T协变:

public interface ICustomService<out T> where T : CustomObject

这将使您的注册try 有效:

services.AddTransient<ICustomService<MyObject>, CustomService1>();
services.AddTransient<ICustomService<MyObject>, CustomService2>();

Covariance确保CustomService1CustomService2可以安全地代替ICustomService<MyObject>使用,尽管它们都声明MyObject子类作为泛型参数.

.net相关问答推荐

无法在Designer、VS2022、. NET 8中打开WinForms表单'

StackExchange.Redis和NRedisStack包有什么不同?

Visual Studio 2022 中的目标操作系统和目标运行时有什么区别?

为什么解码后的字节数组与原始字节数组不同?

线程安全性的单元测试?

将 BitmapImage 转换为 Bitmap,反之亦然

Silverlight 与 Flex

如何将自定义 UserControl 显示为对话框?

使用只读属性或方法?

如何将 NuGet 与 Visual C# Express 一起使用?

你如何调试 MVC 4 API 路由?

如何对无法加载的 VSTO 插件进行故障排除?

无法将文件 *.mdf 作为数据库附加

公钥令牌的作用是什么?

List 和 IEnumerable 的实际区别

设置 System.Drawing.Color 值

.NET 的黄瓜替代品

Find() 和 First() 抛出异常,如何改为返回 null?

如何从其十六进制 RGB 字符串创建 System.Drawing.Color?

如何卸载Microsoft .NET Core 1.0.0 RC2 - VS 2015 Tooling Preview 1?