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

项目突发System.AggregateException错误,求助解决依赖注入问题

问题

项目原本运行正常,突然弹出以下错误:

System.AggregateException: 'Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: Restaurant.DataAccess.Repository.IRepository.IUnitOfWork Lifetime: Scoped ImplementationType: Restaurant.DataAccess.Repository.UnitOfWork': Unable to resolve service for type 'Restaurant.DataAccess.Data.ApplicationDbContext' while attempting to activate 'Restaurant.DataAccess.Repository.UnitOfWork'.)'InvalidOperationException: Unable to resolve service for type 'Restaurant.DataAccess.Data.ApplicationDbContext' while attempting to activate 'Restaurant.DataAccess.Repository.UnitOfWork'.

以下是我的Program.cs代码:

using Microsoft.EntityFrameworkCore;
using Restaurant.DataAccess.Data;
using Restaurant.DataAccess.Repository;
using Restaurant.DataAccess.Repository.IRepository;
using Microsoft.AspNetCore.Identity;


var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(
    builder.Configuration.GetConnectionString("DefaultConnection")));

builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
    .AddEntityFrameworkStores<ApplicationDbContext>();
builder.Services.AddScoped<IUnitOfWork, UnitOfWork>();//Registering CategoryRepository in our dependency injection container

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();
app.UseAuthentication(); ;

app.UseAuthorization();

app.MapRazorPages();
app.MapControllers();//for creating an API in razor project to retriev data in data table ,so we should add map controller in program.cs at first

app.Run();

我尝试修改了Program.cs中UnitOfWork的注册生命周期,但问题仍未解决。

解决方案

这个错误的核心是依赖注入(DI)容器无法在创建UnitOfWork实例时解析ApplicationDbContext,以下是针对性的排查和解决步骤:

  • 检查UnitOfWork构造函数正确性
    确保UnitOfWork的构造函数正确接收ApplicationDbContext参数,且类的命名空间、名称无拼写错误。示例正确的构造函数实现:

    public class UnitOfWork : IUnitOfWork
    {
        private readonly ApplicationDbContext _dbContext;
    
        public UnitOfWork(ApplicationDbContext dbContext)
        {
            _dbContext = dbContext;
            // 其他仓储初始化逻辑
        }
        // 接口实现方法
    }
    

    若构造函数中的ApplicationDbContext存在拼写错误或引用了错误的命名空间,DI容器会无法匹配到对应的服务。

  • 确认ApplicationDbContext注册有效性
    虽然你的代码中ApplicationDbContext注册在UnitOfWork之前(正确顺序),但仍需验证注册是否生效。可在注册UnitOfWork前添加以下代码排查:

    // 在builder.Services.AddScoped<IUnitOfWork, UnitOfWork>();之前插入
    var dbContextService = builder.Services.FirstOrDefault(s => s.ServiceType == typeof(ApplicationDbContext));
    if (dbContextService == null)
    {
        throw new InvalidOperationException("ApplicationDbContext未成功注册到DI容器");
    }
    

    若抛出异常,说明AddDbContext注册逻辑存在问题,需检查后续是否有代码覆盖了该注册。

  • 验证连接字符串配置
    若appsettings.json中DefaultConnection不存在或格式错误,会导致ApplicationDbContext无法正常实例化,间接引发DI解析失败。确认配置文件中的连接字符串正确:

    "ConnectionStrings": {
        "DefaultConnection": "Server=你的数据库服务器地址;Database=RestaurantDb;Trusted_Connection=True;TrustServerCertificate=True;"
    }
    
  • 清理重建项目
    缓存或编译产物异常也可能导致DI问题,执行以下操作:

    1. 右键项目选择「清理」
    2. 删除项目目录下的bin和obj文件夹
    3. 右键项目选择「生成」
    4. 重启开发工具后重新运行项目

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 20:47:35