c# - 如何添加通用依赖注入(inject)

标签 c# generics dependency-injection asp.net-core .net-core

<分区>

使用只读 API 服务并使用泛型将操作打包到基于约定的流程中。

存储库接口(interface):

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

Controller :

public class EmployeeController : Controller {
   public EmployeeController(IRepository<int,Employee> repo) {//stuff}
}

我目前正在为 ConfigureServices 中所有类型的实体类型重复存储库实现。 .有没有办法使它也通用?

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

那么在controller的constructor调用中可以自动获取相关的repository吗?

更新 1:不是 duplicate :

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

最佳答案

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

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

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

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

关于c# - 如何添加通用依赖注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43087821/

相关文章:

c# - .NET 3rd 方库中是否有任何并发​​队列类型?

c# - 将 MVC 1 应用程序部署到远程服务器时 Global.asax 解析器错误

java - 我如何知道何时使用 Stack 而不是其他 Collections?

java - 为什么我不能用接口(interface)来做这个?

java - 编写一个名为 Child 的简单接口(interface)(其中没有任何内容),并使用它创建一个只能存储 Boy 和 Girl 实例的 ArrayList

.net - 如何根据传递给 VB.NET 泛型方法的类型执行条件逻辑

c# - 无法在 Xamarin.iOS 中为微光设置动画渐变层

java - 使用配置文件的 Spring 默认接线

dependency-injection - ASP.NET Core 内置 DI 系统中的 DI Modules

c# - 简单注入(inject)器:如何跳过对容器中对象的验证