繁体   English   中英

如何添加通用依赖注入

[英]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 :不重复

  1. 存储库实现没有默认构造函数
  2. 因为它没有默认构造函数,所以我无法提供链接问题中给出的解决方案。
  3. 尝试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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM