c# - 带参数的开放泛型的依赖注入(inject)

标签 c# .net-core dependency-injection

This文章讨论了如何在 .Net Core 中注册通用接口(interface)。但是,我有一个具有多个参数的通用接口(interface),并且无法弄清楚注册和构造函数注入(inject)。
我的接口(interface)有 4 个参数

public class TestImplementation 
{
    // Try to inject IRepository here ??????
    public TestImplementation(.......)
    {
        ...
    }
}

public class Repository : IRepository<Test1, Test2, Test3, Test4> 
{
    ...
}

public interface IRepository<T, U, V, W> where T : ITemplate1 where U : ITemplate2,...  
{
    ...
}
如果我尝试将接口(interface)注入(inject)任何类,它会给我错误,因为即使在代码的其他部分使用下面的代码,接口(interface)也没有得到解决
services.GetService(typeof(IRepository<,,,>))
我尝试使用构造函数注入(inject),但它使编译器不满意(在尝试激活 xxxx 时无法解析类型 '....Interface....' 的服务),因为我想保持接口(interface)打开。然而,我解决了代码中的接口(interface)

最佳答案

正确的做法是不注入(inject)Repository服务。它应该仅用作具有功能的模板。然后创建一个继承自 Repository 的附加类。类和继承自 IRepository 的接口(interface).这样你就可以分配通用值的值,然后以一种整洁和可控的方式注入(inject)它。
起初,这种模式可能看起来有点额外的工作,但它允许为每个表存储库自定义功能,明确您正在使用哪个表,并允许轻松替换不同的数据库。请参阅下面的示例:
因此,如您所愿,创建您的 RepositoryIRepository界面:

public abstract class Repository<T, U, V, W> : IRepository<T, U, V, W> 
{
    ...
}

public interface IRepository<T, U, V, W> where T : ITemplate1 where U : ITemplate2,...  
{
    ...
}
现在为您的特定表创建一个接口(interface)。先上界面:
public interface ISomeTableRepository : IRepository<input_1, input_2, ...> {}
现在创建类存储库:
public class SomeTableRepository : Repository<input_1, input_2,...> , ISomeTableRepository {}
现在,您将这些注册到您的 Startup.cs 中没有输入的新存储库中。文件。
services.AddScoped<ISomeTableRepository, SomeTableRepository> ();
现在您可以轻松注入(inject)它,无需添加参数:
public class TestImplementation 
{
    readonly ISomeTableRepository _someTable;

    
    public TestImplementation(ISomeTableRepository someTable)
    {
        _someTable = someTable;
    }
}

关于c# - 带参数的开放泛型的依赖注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68089857/

相关文章:

c# - AWS .NET Core单元测试加载非默认配置文件

c# - .Net Core 2.2 Web API 在 GET 上获取 415 不支持的媒体类型?

c# - 使用泛型从字符串中解析集合名称

c# - Entity Framework 实体的 DI

java - 不完整父级上 Dagger .plus() 的回溯

javascript - 我有一个 **Rad 组合框**,其中有两个分隔符。如何仅从分隔符中删除复选框?

c# - dll自定义业务逻辑

c# - 如何在 C# 中以编程方式创建柔和的颜色?

c# - 使用客户端 key 的 Azure 和 Microsoft Graph : Access denied accessing inbox,

android - Dagger2,提供不同URL的Retrofit实例