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)它。
起初,这种模式可能看起来有点额外的工作,但它允许为每个表存储库自定义功能,明确您正在使用哪个表,并允许轻松替换不同的数据库。请参阅下面的示例:
因此,如您所愿,创建您的 Repository
和 IRepository
界面:
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/