带参数的开放泛型的依赖注入

Ank*_*kit 4 c# dependency-injection .net-core

文章谈到如何在.net核心注册的通用接口。但是,我有一个具有多个参数的通用接口,并且无法弄清楚注册和构造函数注入。

我的接口有 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,...  
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

如果我尝试将接口注入任何类,它会给我错误,因为即使在代码的其他部分使用下面的代码,接口也没有得到解决

services.GetService(typeof(IRepository<,,,>))
Run Code Online (Sandbox Code Playgroud)

我尝试使用构造函数注入,但它使编译器不满意(在尝试激活 xxxx 时无法解析类型 '....Interface....' 的服务),因为我想保持接口打开。然而,我解决了代码中的接口

use*_*845 7

正确的方法是不注入Repository服务。它应该仅用作具有功能的模板。然后创建一个继承自Repository该类的附加类和一个继承自 的接口IRepository。这样你就可以分配通用值的值,然后以一种整洁和可控的方式注入它。

起初,这种模式可能看起来有点额外的工作,但它允许为每个表存储库自定义功能,明确您正在使用哪个表,并允许轻松替换不同的数据库。请参阅下面的示例:

所以,正如你所拥有的,创建你的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,...  
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

现在为您的特定表创建一个接口。先上界面:

public interface ISomeTableRepository : IRepository<input_1, input_2, ...> {}
Run Code Online (Sandbox Code Playgroud)

现在创建类存储库:

public class SomeTableRepository : Repository<input_1, input_2,...> , ISomeTableRepository {}
Run Code Online (Sandbox Code Playgroud)

现在您将这些注册到您的Startup.cs文件中没有输入的新存储库。

services.AddScoped<ISomeTableRepository, SomeTableRepository> ();
Run Code Online (Sandbox Code Playgroud)

现在您可以轻松注入它,无需添加参数:

public class TestImplementation 
{
    readonly ISomeTableRepository _someTable;

    
    public TestImplementation(ISomeTableRepository someTable)
    {
        _someTable = someTable;
    }
}
Run Code Online (Sandbox Code Playgroud)