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

ASP.NET Core MVC 6.0执行Add-Migration时出现依赖注入异常

ASP.NET Core Identity v6.0 Add-Migration 异常解决

异常核心原因

执行Add-Migration时抛出的异常,核心问题是依赖注入容器无法解析Microsoft.EntityFrameworkCore.DbContext类型的服务,导致Identity相关的UserStore、RoleStore等组件无法被激活,进而引发一系列服务构造失败。同时提示无法创建DbContext对象,这通常和设计时DbContext的配置逻辑有关。

解决方案

1. 修正DbContext的注册方式

确保在Program.cs中注册自定义DbContext,而非泛型的DbContext:

// 错误示例:注册泛型DbContext
builder.Services.AddDbContext<DbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

// 正确示例:注册你的自定义DbContext(如AppDbContext)
builder.Services.AddDbContext<AppDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

2. 绑定Identity与自定义DbContext

配置Identity时,明确指定使用你的自定义DbContext:

builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
    .AddEntityFrameworkStores<AppDbContext>(); // 此处传入自定义DbContext类型

3. 完善DbContext设计时支持

针对设计时无法创建DbContext的问题,可通过两种方式解决:

  • 方式一:添加正确的构造函数
    给自定义DbContext添加接受DbContextOptions<T>的构造函数:
    public class AppDbContext : IdentityDbContext<IdentityUser, IdentityRole, string>
    {
        public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
        {
        }
    }
    
  • 方式二:实现设计时工厂
    当无法通过依赖注入获取配置时,实现IDesignTimeDbContextFactory<T>接口:
    public class AppDbContextFactory : IDesignTimeDbContextFactory<AppDbContext>
    {
        public AppDbContext CreateDbContext(string[] args)
        {
            var configuration = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json")
                .Build();
    
            var optionsBuilder = new DbContextOptionsBuilder<AppDbContext>();
            optionsBuilder.UseSqlServer(configuration.GetConnectionString("DefaultConnection"));
    
            return new AppDbContext(optionsBuilder.Options);
        }
    }
    

4. 统一NuGet包版本

确保所有相关包的版本保持6.0.x一致:

  • Microsoft.AspNetCore.Identity.EntityFrameworkCore
  • Microsoft.EntityFrameworkCore
  • Microsoft.EntityFrameworkCore.Tools
  • Microsoft.EntityFrameworkCore.SqlServer(若使用SQL Server)

5. 清理重建项目

执行以下命令后重新尝试迁移:

dotnet clean
dotnet build
Add-Migration InitialCreate

内容的提问来源于stack exchange,提问作者Muhammad Azib Ali

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 13:10:55