Asp.NET Core 6集成Identity后IUnitOfWork服务构造失败求助
我正在开发Asp.NET Core 6.0项目,已集成Microsoft Identity组件并添加Razor页面。同时创建类库项目,实现了Entity Framework的DataContext、IUnitOfWork及仓储模式,并在Program.cs中注册UnitOfWork。项目编译正常,但运行时出现以下错误:
System.AggregateException: 'Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: eGrantsEvo.DataAccess.Repository.Interfaces.IUnitOfWork Lifetime: Scoped ImplementationType: eGrantsEvo.DataAccess.Repository.UnitOfWork': Unable to resolve service for type 'eGrantsEvo.DataAccess.EGrantsEvoDbContext' while attempting to activate 'eGrantsEvo.DataAccess.Repository.UnitOfWork'.)'
InvalidOperationException: Unable to resolve service for type 'eGrantsEvo.DataAccess.EGrantsEvoDbContext' while attempting to activate 'eGrantsEvo.DataAccess.Repository.UnitOfWork'.
相关代码片段:
Program.cs
var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllersWithViews(); builder.Services.AddDbContext<EGrantsEvoDbContext>(options => options.UseSqlServer( builder.Configuration.GetConnectionString("DefaultConnectionString") )); builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true) .AddEntityFrameworkStores<EGrantsEvoDbContext>(); builder.Services.AddScoped<IUnitOfWork, UnitOfWork>(); builder.Services.AddRazorPages().AddRazorRuntimeCompilation(); var app = builder.Build();
IUnitOfWork
public interface IUnitOfWork { IUserRepository User { get; } void Save(); }
UnitOfWork
public class UnitOfWork : IUnitOfWork { private readonly EGrantsEvoDbContext _dbContext; public IUserRepository User { get; private set; } public UnitOfWork(EGrantsEvoDbContext dbContext) { _dbContext = dbContext; User = new UserRepository(_dbContext); } public void Save() { _dbContext.SaveChanges(); } }
错误核心是依赖注入容器无法找到EGrantsEvoDbContext的注册实例,导致创建UnitOfWork时无法注入所需上下文。以下是具体解决思路:
- 检查命名空间引用:确保Program.cs中已正确引用
EGrantsEvoDbContext所在的eGrantsEvo.DataAccess命名空间,未添加引用会导致DI容器无法识别该类型。 - 确认DbContext构造函数符合要求:如果
EGrantsEvoDbContext继承自IdentityDbContext,需保证构造函数正确传递DbContextOptions给基类,示例如下:public class EGrantsEvoDbContext : IdentityDbContext<IdentityUser> { public EGrantsEvoDbContext(DbContextOptions<EGrantsEvoDbContext> options) : base(options) { } // 其他DbSet定义 } - 验证生命周期匹配:默认
AddDbContext注册的是Scoped生命周期服务,UnitOfWork也是Scoped,二者生命周期需保持一致,避免手动指定不同生命周期导致冲突。 - 检查类库引用:确认Web项目已添加包含
EGrantsEvoDbContext的类库项目引用,未引用会导致DI容器找不到类型定义。 - 核对连接字符串:检查
appsettings.json中DefaultConnectionString的名称和内容是否正确,连接字符串配置错误可能间接导致DbContext初始化失败。
内容的提问来源于stack exchange,提问作者Massey

