C# 如何将DI与泛型类型接口的许多不同实现一起使用?

C# 如何将DI与泛型类型接口的许多不同实现一起使用?,c#,generics,design-patterns,dependency-injection,interface,C#,Generics,Design Patterns,Dependency Injection,Interface,我正在尝试创建一个聚合器,该聚合器可以循环通过一个接口(icontentereder)的多个实现,该接口的泛型类型被约束到另一个接口(IContent)。icontentereader的每个实现都将使用不同的“IContent”接口实现。这似乎不适用于DI。我有点不知所措,不知该怎么做 随着时间的推移,我的需求将不断扩大,以包括每款都有自己的阅读器和内容的新游戏。如何使这成为一个DI友好的解决方案 以下是泛型类型的接口: public interface IContentReader<TC

我正在尝试创建一个聚合器,该聚合器可以循环通过一个接口(
icontentereder
)的多个实现,该接口的泛型类型被约束到另一个接口(
IContent
)。
icontentereader
的每个实现都将使用不同的“IContent”接口实现。这似乎不适用于DI。我有点不知所措,不知该怎么做

随着时间的推移,我的需求将不断扩大,以包括每款都有自己的阅读器和内容的新游戏。如何使这成为一个DI友好的解决方案

以下是泛型类型的接口:

public interface IContentReader<TContent> where TContent: IContent
{    
    IList<TContent> Content { get; }

    void Read(string file);
}
这是一个聚合器的示例,它将在实现中循环:

public class ContentReaderAggregator : IContentReaderAggregator
{
    private readonly IEnumerable<IContentReader<IContent>> _readers;


    public ContentReaderAggregator(IEnumerable<IContentReader<IContent>> readers)
    {
        _readers = readers;
    }


    public void Read(string file)
    {
        foreach (var reader in _readers)
            reader.Read(file);
    }
}
公共类ContentReaderAggregator:IContenterederAggregator
{
私有只读IEnumerable_阅读器;
公共内容阅读器聚合器(IEnumerable readers)
{
_读者=读者;
}
公共无效读取(字符串文件)
{
foreach(变量读取器在_读取器中)
reader.Read(文件);
}
}
内容类型和读取器的示例实现:

public class Game1Content : IContent
{
    public int Id { get; private set; }
}

public class Game1ContentReader : IContentReader<Game1Content>
{
    public IList<Game1Content> Content { get; }
    
    public void Read(string file)
    {
        //Read implementation code
    }
}
公共类游戏1内容:IContent
{
public int Id{get;private set;}
}
公共类游戏1联系人:IContentereder
{
公共IList内容{get;}
公共无效读取(字符串文件)
{
//读取实现代码
}
}
当我尝试创建
icontentereder
实现的集合时,遇到的编译器错误是


我在很大程度上理解这个转换错误,所以我更想问的是,从哲学/设计模式的角度来看,我做错了什么。

制作
icontentereder
会有帮助吗?顺便问一下,为什么
IContent
是一个界面?“你打算用多种方式实现这个getter吗?”MarkSeemann回答你的第一个问题,我不确定,但谢谢你的链接!我会仔细阅读的。关于第二个问题:为了简洁起见,我从
IContent
中删除了一些复杂性。对于我的实际情况,我相信一个接口是必要的。你的问题是关于实现,我应该使用抽象类,因为接口是行为签名吗?不,我的问题是因为内部多态性可能会给你带来问题,因此关于协方差的问题。如果
IContent
仅包含数据(即getter和setter),则没有理由使其具有多态性。如果它确实包含多态行为(即方法),那就另当别论了。如前所述,您可以将
void Read(string file)
推送到
icontenterbase
(非通用)接口并使用它,但您可能还有其他要求?
public class Game1Content : IContent
{
    public int Id { get; private set; }
}

public class Game1ContentReader : IContentReader<Game1Content>
{
    public IList<Game1Content> Content { get; }
    
    public void Read(string file)
    {
        //Read implementation code
    }
}