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

ASP.NET Core 7.0中如何从Program.cs的WebApplication获取UserManager实例?

问题描述

我需要在Program.cs文件中获取UserManager实例以初始化IdentityUser数据,以下是我的代码片段:

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<AppDbContext>(options =>
    options.UseSqlServer(connectionString));
builder.Services.AddDatabaseDeveloperPageExceptionFilter();

builder.Services
    .AddDefaultIdentity<MyIdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
    .AddRoles<IdentityRole>()
    .AddEntityFrameworkStores<AppDbContext>();

builder.Services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
});

builder.Services.AddRazorPages();
builder.Services.AddControllersWithViews();


builder.Services.AddScoped(typeof(IRepository<>), typeof(Repository<>));

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseMigrationsEndPoint();
}
else
{
    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.MapControllers();

app.MapControllerRoute(
        name: "default",
        pattern: "{controller = Home}/{action = Index}/{Id?}"
    );
app.UseRouting();

app.UseAuthentication();
app.UseAuthorization();

app.MapDefaultControllerRoute();
app.MapRazorPages();

var scopeFactory = app.Services.GetRequiredService<IServiceScopeFactory>();
var scope = scopeFactory.CreateScope();
var roleManager = scope.ServiceProvider.GetRequiredService<RoleManager<IdentityRole>>();
var userManager = scope.ServiceProvider.GetRequiredService<UserManager<MyIdentityUser>>();

SeedInitialData.SeedData(roleManager, userManager);

app.Run();

运行时收到如下异常:

InvalidOperationException: No service for type 'Microsoft.AspNetCore.Identity.UserManager`1[Microsoft.AspNetCore.Identity.IdentityUser]' has been registered.
Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)

尝试多种方法均未解决,恳请协助排查。

排查与解决方案

核心问题

你注册的是自定义用户类型MyIdentityUser对应的UserManager,但异常显示系统在尝试获取默认IdentityUser类型的UserManager,根源是**SeedInitialData.SeedData方法的参数类型声明不匹配**——它大概率定义为UserManager<IdentityUser>,而非你实际使用的UserManager<MyIdentityUser>。

解决步骤

  1. 修正SeedData方法签名
    打开SeedInitialData类,确保SeedData方法的参数类型与自定义用户类型一致:
    public static void SeedData(RoleManager<IdentityRole> roleManager, UserManager<MyIdentityUser> userManager)
    {
        // 你的初始化逻辑代码
    }
    
  2. 确认自定义用户类继承关系
    检查MyIdentityUser是否正确继承自IdentityUser,避免类型不兼容:
    public class MyIdentityUser : IdentityUser
    {
        // 自定义属性(如有)
    }
    
  3. 规范作用域释放(可选优化)
    当前代码创建的服务作用域未手动释放,虽然框架会自动处理,但显式释放更符合最佳实践:
    using (var scope = scopeFactory.CreateScope())
    {
        var roleManager = scope.ServiceProvider.GetRequiredService<RoleManager<IdentityRole>>();
        var userManager = scope.ServiceProvider.GetRequiredService<UserManager<MyIdentityUser>>();
        SeedInitialData.SeedData(roleManager, userManager);
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 19:00:59