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

.NET 6激活GenericRepository时无法解析DbSet服务的问题

问题排查:无法解析DbSet服务的错误

错误信息

System.InvalidOperationException: 尝试激活'Drin.Data.Repositories.GenericRepository1[Entities.Product]'时,无法解析类型为'Microsoft.EntityFrameworkCore.DbSet1[Entities.Product]'的服务。

相关代码

SampleDbContext代码

public class SampleDbContext : DbContext
{
    public SampleDbContext(DbContextOptions<SampleDbContext> options) : base(options) {
        
    }

    public DbSet<Category>  Category { get; set; }
    public DbSet<Product> Product { get; set; }
    public DbSet<ProductFeature> ProductFeature { get; set; }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        builder.ApplyConfigurationsFromAssembly(Assembly.GetExecutingAssembly());     

        builder.Entity<ProductFeature>().HasData(
            new ProductFeature { Id = 1, Colour = "Black", Weight = 40, ProductId = 1 },
            new ProductFeature { Id = 2, Colour = "Blue", Weight = 10, ProductId = 2 });


        base.OnModelCreating(builder);
    }
}

Program.cs代码

builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

builder.Services.AddScoped<IUnitOfWork, UnitOfWork>();
builder.Services.AddScoped(typeof(IGenericRepository<>), typeof(GenericRepository<>));
builder.Services.AddScoped(typeof(IService<>), typeof(Service<>));
builder.Services.AddAutoMapper(typeof(MapProfile));

builder.Services.AddDbContext<SampleDbContext>(x =>
{
    x.UseSqlServer(builder.Configuration.GetConnectionString("DevConnection"), options =>
    {
        options.MigrationsAssembly(Assembly.GetAssembly(typeof(SampleDbContext)).GetName().Name);
    });
});

GenericRepository代码

public class GenericRepository<T> : IGenericRepository<T> where T : class
{
    private readonly SampleDbContext context;
    private readonly DbSet<T> dbSet;

    public GenericRepository(SampleDbContext context, DbSet<T> dbSet)
    {
        this.context = context;
        this.dbSet = context.Set<T>();
    }

    public async Task AddAsync(T entity)
    {
        await dbSet.AddAsync(entity);
    } 
}

原因分析

  1. 依赖注入(DI)容器中未注册DbSet<T>类型的服务,而GenericRepository<T>的构造函数声明需要注入该类型,导致DI无法找到对应服务实现解析依赖。
  2. 冗余设计:构造函数内部已经通过context.Set<T>()获取了DbSet<T>实例,完全没必要将DbSet<T>作为构造参数传入。

解决方法

修改GenericRepository<T>的构造函数,移除DbSet<T>参数,仅保留SampleDbContext注入:

public class GenericRepository<T> : IGenericRepository<T> where T : class
{
    private readonly SampleDbContext context;
    private readonly DbSet<T> dbSet;

    public GenericRepository(SampleDbContext context)
    {
        this.context = context;
        this.dbSet = context.Set<T>();
    }

    public async Task AddAsync(T entity)
    {
        await dbSet.AddAsync(entity);
    } 
}

修改后,DI容器可正常解析已注册的SampleDbContext,同时仍能通过上下文获取对应DbSet<T>实例,错误即可解决。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 20:20:26