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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 23:02:06