如何添加通用依赖注入 [英] How to add a generic dependency injection
问题描述
致力于只读 api 服务并利用泛型将操作打包到基于约定的流程中.
Working on a read-only api service and making use of generics to package the operation into convention based process.
存储库接口:
public interface IRepository<TIdType,TEntityType> where TEntityType:class {
Task<EntityMetadata<TIdType>> GetMetaAsync();
}
存储库实现:
public class Repository<TIdType,TEntityType> : IRepository<TIdType,TEntityType> where TEntityType:class {
public Repository(string connectionString) { // initialization }
public async Tas<EntityMetadata<TIdType>> GetMetaAsync() { // implementation }
}
在 Startup.cs 中 ->配置服务
:
services.AddSingleton<IRepository<int, Employee>> ( p=> new Repository<int, Employee>(connectionString));
services.AddSingleton<IRepository<int, Department>> ( p=> new Repository<int, Department>(connectionString));
// and so on
控制器:
public class EmployeeController : Controller {
public EmployeeController(IRepository<int,Employee> repo) {//stuff}
}
我目前正在为 ConfigureServices
中的所有类型的实体类型重复存储库实现.有没有办法让它也通用?
I am currently repeating the repository implmentation for all types of entity types in the ConfigureServices
. Is there a way to make this generic too?
services.AddSingleton<IRepository<TIdType, TEntityType>> ( p=> new Repository<TIdType, TEntityType>(connectionString));
那么在控制器构造函数中调用可以自动获取相关的repository?
so in the controller constructor call can automatically get the relevant repository?
更新 1:不是重复:
- 存储库实现没有默认构造函数
- 因为它没有默认构造函数,所以我无法提供链接问题中给出的解决方案.
- 在尝试
services.AddScoped(typeof(IRepository<>), ...)
时出现错误Using the generic type 'IRepostiory
'需要 2 个类型参数
- The repository implementation does not have default constructor
- Because it does not have default constructor, I cannot provide the solution given in the linked question.
- When trying
services.AddScoped(typeof(IRepository<>), ...)
I am getting errorUsing the generic type 'IRepostiory<TIdType,TEntityType>' requires 2 type arguments
推荐答案
由于此问题仍未正确标记为 duplicate:注册泛型类的方法:
Since this question is still not properly marked as duplicate: The way to register a Generic class:
services.AddScoped(typeof(IRepository<,>), typeof(Repository<,>));
现在您可以通过以下方式解决它:
now you can resolve it in the following way:
serviceProvider.GetService(typeof(IRepository<A,B>));
// or: with extensionmethod
serviceProvider.GetService<IRepository<A,B>>();
这篇关于如何添加通用依赖注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!