如何添加通用依赖注入 [英] How to add a generic dependency injection

查看:25
本文介绍了如何添加通用依赖注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

致力于只读 api 服务并利用泛型将操作打包到基于约定的流程中.

Working on a read-only api service and making use of generics to package the operation into convention based process.

存储库接口:

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 中 ->配置服务:

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 中的所有类型的实体类型重复存储库实现.有没有办法让它也通用?

I am currently repeating the repository implmentation for all types of entity types in the ConfigureServices. Is there a way to make this generic too?

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

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

so in the controller constructor call can automatically get the relevant repository?

更新 1:不是重复:

  1. 存储库实现没有默认构造函数
  2. 因为它没有默认构造函数,所以我无法提供链接问题中给出的解决方案.
  3. 在尝试 services.AddScoped(typeof(IRepository<>), ...) 时出现错误 Using the generic type 'IRepostiory'需要 2 个类型参数
  1. The repository implementation does not have default constructor
  2. Because it does not have default constructor, I cannot provide the solution given in the linked question.
  3. When trying services.AddScoped(typeof(IRepository<>), ...) I am getting error Using the generic type 'IRepostiory<TIdType,TEntityType>' requires 2 type arguments

推荐答案

由于此问题仍未正确标记为 duplicate:注册泛型类的方法:

Since this question is still not properly marked as duplicate: The way to register a Generic class:

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

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

now you can resolve it in the following way:

serviceProvider.GetService(typeof(IRepository<A,B>));
// or: with extensionmethod
serviceProvider.GetService<IRepository<A,B>>();

这篇关于如何添加通用依赖注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆