如何添加通用dependency injection

使用只读api服务并利用generics将操作打包到基于约定的过程中。

存储库界面:

public interface IRepository where TEntityType:class { Task<EntityMetadata> GetMetaAsync(); } 

存储库实现:

 public class Repository : IRepository where TEntityType:class { public Repository(string connectionString) { // initialization } public async Tas<EntityMetadata> GetMetaAsync() { // implementation } } 

Startup.cs -> ConfigureServices

 services.AddSingleton<IRepository> ( p=> new Repository(connectionString)); services.AddSingleton<IRepository> ( p=> new Repository(connectionString)); // and so on 

控制器:

 public class EmployeeController : Controller { public EmployeeController(IRepository repo) {//stuff} } 

我目前正在重复ConfigureServices所有类型的实体类型的存储库实现。 有没有办法让这个通用呢?

 services.AddSingleton<IRepository> ( p=> new Repository(connectionString)); 

那么在控制器构造函数中调用可以自动获取相关的存储库吗?

更新1 :不重复 :

  1. 存储库实现没有默认构造函数
  2. 因为它没有默认构造函数,所以我无法提供链接问题中给出的解决方案。
  3. 尝试services.AddScoped(typeof(IRepository), ...)我收到错误Using the generic type 'IRepostiory' requires 2 type arguments

由于此问题仍未正确标记为重复 :注册Generic类的方法:

 services.AddScoped(typeof(IRepository<,>), typeof(Repository<,>)); 

现在您可以通过以下方式解决它:

 serviceProvider.GetService(typeof(IRepository)); // or: with extensionmethod serviceProvider.GetService>();