You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET依赖注入报错:无法为IAuditRepository[T]实例化AuditRepository[T]

泛型仓储依赖注入报错:无法为IAuditRepository[T]实例化AuditRepository[T]

错误信息:

Cannot instantiate implementation type AuditRepository[T] for service type IAuditRepository[T]

已经排查过所有常见诱因(比如实现类是抽象类),但都不符合我的情况。

相关代码

Program.cs

builder.Services.AddScoped(typeof(IAuditRepository<>), typeof(AuditRepository<>));

IAuditRepository.cs

public interface IAuditRepository<T> where T : class
{
   Task<Audit> GetByEntity(T entity);
}

AuditRepository.cs

public class AuditRepository<T> : IAuditRepository<T> where T : class
{
   private readonly AppDbContext context;

   public AuditRepository(AppDbContext context)
   {
      this.context = context;
   }
   
   public async Task<Audit> GetByEntity(T entity)
   {
      ...
   }
}

说明:我有大量实体类,所以像下面这样逐个注册根本不现实:

builder.Services.AddScoped(typeof(IAuditRepository<CustomerAccount>), typeof(AuditRepository<CustomerAccount>));
builder.Services.AddScoped(typeof(IAuditRepository<Quote>), typeof(AuditRepository<Quote>));
builder.Services.AddScoped(typeof(IAuditRepository<Address>), typeof(AuditRepository<Address>));
....
....

内容的提问来源于stack exchange,提问作者Pavel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 10:52:42