【发布时间】:2017-08-22 14:31:35
【问题描述】:
开发一个只读的 api 服务并利用泛型将操作打包到基于约定的流程中。
存储库接口:
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
控制器:
public class EmployeeController : Controller {
public EmployeeController(IRepository<int,Employee> repo) {//stuff}
}
我目前正在为ConfigureServices 中的所有类型的实体类型重复存储库实现。有没有办法让这个也通用?
services.AddSingleton<IRepository<TIdType, TEntityType>> ( p=> new Repository<TIdType, TEntityType>(connectionString));
那么在控制器的构造函数调用中可以自动获取相关的仓库吗?
更新 1:不是duplicate:
- 存储库实现没有默认构造函数
- 由于它没有默认构造函数,我无法提供链接问题中给出的解决方案。
- 尝试
services.AddScoped(typeof(IRepository<>), ...)时出现错误Using the generic type 'IRepostiory<TIdType,TEntityType>' requires 2 type arguments
【问题讨论】:
-
从技术上讲,它是重复的。但是当你有 2 个参数时,你必须使用
typeof(IRepository<,>)而不是typeof(IRepository<>)因为它有两个通用参数 -
@Tseng 你能否提一下如何启动存储库的构造函数?也许将其添加为答案,我可以将其标记为完成。
-
启动是什么意思?具体实现的构造函数中的任何参数(即
GenericRepository<TIdType,TEntityType>将由IoC容器解析。在需要它的服务中,您可以通过IRepository<int,User>请求它 -
@Tseng 请完成完整的问题
标签: c# generics dependency-injection asp.net-core .net-core