[英]How to add Dependency Injection into a stateless service with a generic OwinCommunicationsListener
[英]How to add a generic dependency injection
使用只读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 :不重复 :
services.AddScoped(typeof(IRepository<>), ...)
我收到错误Using the generic type 'IRepostiory<TIdType,TEntityType>' requires 2 type arguments
由于此问题仍未正确标记为重复 :注册Generic类的方法:
services.AddScoped(typeof(IRepository<,>), typeof(Repository<,>));
现在您可以通过以下方式解决它:
serviceProvider.GetService(typeof(IRepository<A,B>));
// or: with extensionmethod
serviceProvider.GetService<IRepository<A,B>>();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.