【发布时间】:2021-06-22 19:40:39
【问题描述】:
This 文章讨论了如何在 .Net Core 中注册通用接口。但是,我有一个具有多个参数的通用接口,并且无法确定注册和构造函数注入。
我的接口有 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,...
{
...
}
如果我尝试将接口注入任何类,它会给我错误,因为即使在代码的其他部分中使用下面的代码也无法解析接口
services.GetService(typeof(IRepository<,,,>))
我尝试使用构造函数注入,但它使编译器不满意(尝试激活 xxxx 时无法解析类型“....接口....”的服务),因为我想保持接口打开。但是我在代码中解析了接口
【问题讨论】:
-
您的代码目前包含无效语法,因此很难看出这不是the question you link to 的重复。
TestRepository : Repository<Test>是不可能的,因为Repository不是泛型类。Repository实现了IRepository但似乎没有指定接口所需的类型。 -
我清理了代表问题的代码
-
受链接问题中答案的启发,这应该可以工作:
services.AddScoped(typeof(IRepository<Test1, Test2, Test3, Test4>), typeof(Repository));,然后在构造函数中:public TestImplementation(IRepository<Test1, Test2, Test3, Test4> repo) -
你不能
services.GetService(typeof(IRepository<,,,>))因为你得到的服务必须是一个 constructed 泛型类型,即它必须指定所有类型参数,例如services.GetService(typeof(IRepository<int, string, float, bool>))。如果您只想向容器注册一个构造的泛型类型,那么这很容易:services.AddScoped<IRepository<int, string, float, bool>, MyRepositoryImpl>()。如果你想在容器中注册开放的泛型,你需要一个更高级的 DI 框架,比如 Autofac。 -
糟糕,我错了——你可以用
services.AddScoped(typeof(IRepository<,,,>), typeof(MyRepositoryImpl<,,,>))之类的东西注册开放的泛型。我假设泛型类型参数的数量必须与服务类型和实现类型相匹配。
标签: c# .net-core dependency-injection