ASP.NET Core项目启动触发System.AggregateException的解决求助
解决ASP.NET Core启动时的System.AggregateException问题
错误核心原因
从错误信息里的Unable to resolve service for type 'eProject3.Data.ApplicationDbContext'可以明确两点:
- Identity相关服务(如
UserManager、SignInManager)依赖ApplicationDbContext,但你没有将这个DbContext注册到依赖注入容器——代码里注册DbContext的代码被注释掉了。 - 存在命名空间不匹配:代码里引用的是
MB3.Data,但错误提示中DbContext属于eProject3.Data,二者需要统一。
修复步骤
恢复DbContext的注册代码
取消Program.cs中被注释的AddDbContext代码块,同时修正命名空间:要么把using语句改为using eProject3.Data;,要么调整ApplicationDbContext所在的项目命名空间为MB3.Data,保证二者一致。验证连接字符串配置
检查appsettings.json里的DefaultConnection是否正确指向你的SQL Server数据库,示例配置:"ConnectionStrings": { "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=eProject3;Trusted_Connection=True;MultipleActiveResultSets=true" }执行数据库迁移(首次搭建时)
如果是第一次配置数据库,需要执行迁移命令初始化数据库:- 使用Package Manager Console:
Add-Migration InitialCreate Update-Database - 使用.NET CLI终端:
dotnet ef migrations add InitialCreate dotnet ef database update
- 使用Package Manager Console:
修正后的Program.cs代码示例
using eProject3.Data; // 确保命名空间与错误提示一致 using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; var builder = WebApplication.CreateBuilder(args); // Add services to the container. var connectionString = builder.Configuration.GetConnectionString("DefaultConnection"); // 恢复DbContext注册 builder.Services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(connectionString)); builder.Services.AddDatabaseDeveloperPageExceptionFilter(); builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true) .AddEntityFrameworkStores<ApplicationDbContext>(); builder.Services.AddControllersWithViews(); var app = builder.Build(); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.UseMigrationsEndPoint(); } else { app.UseExceptionHandler("/Home/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); app.MapRazorPages(); app.Run();
内容的提问来源于stack exchange,提问作者Noo
相关产品推荐
相关产品推荐

