.NET 6激活GenericRepository时无法解析DbSet服务的问题
问题排查:无法解析DbSet服务的错误
错误信息
System.InvalidOperationException: 尝试激活'Drin.Data.Repositories.GenericRepository
1[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); } }
原因分析
- 依赖注入(DI)容器中未注册
DbSet<T>类型的服务,而GenericRepository<T>的构造函数声明需要注入该类型,导致DI无法找到对应服务实现解析依赖。 - 冗余设计:构造函数内部已经通过
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
相关产品推荐
相关产品推荐

