<分区>
使用只读 API 服务并使用泛型将操作打包到基于约定的流程中。
存储库接口(interface):
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 -> ConfigureServices
:
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
Controller :
public class EmployeeController : Controller {
public EmployeeController(IRepository<int,Employee> repo) {//stuff}
}
我目前正在为 ConfigureServices
中所有类型的实体类型重复存储库实现。 .有没有办法使它也通用?
services.AddSingleton<IRepository<TIdType, TEntityType>> ( p=> new Repository<TIdType, TEntityType>(connectionString));
那么在controller的constructor调用中可以自动获取相关的repository吗?
更新 1:不是 duplicate :
- 存储库实现没有默认构造函数
- 因为它没有默认构造函数,所以我无法提供链接问题中给出的解决方案。
- 尝试时
services.AddScoped(typeof(IRepository<>), ...)
我收到错误Using the generic type 'IRepostiory<TIdType,TEntityType>' requires 2 type arguments