ASP.Net 6 类型“Microsoft.AspNetCore.Identity.UserManager”没有服务

ASP.Net 6 No service for type 'Microsoft.AspNetCore.Identity.UserManager

提问人:RJPWilliams 提问时间:11/15/2023 更新时间:11/15/2023 访问量:14

问:

我一直在尝试在启动.cs中设置角色和用户。我现在的角色可以工作,但用户无法生成“类型'Microsoft.AspNetCore.Identity.UserManager'没有服务”。我花了半天时间浏览了 stackoverflow 和其他网站上给出的解决方案,包括 learn.microsoft.com 上的示例,但我离解决方案越来越近了。我已经删除了我尝试过的所有添加,但都失败了,并回到了角色工作但用户不起作用的地方。 ApplicationDBContext 如下所示:

public class ApplicationDbContext : IdentityDbContext<BOAPUser>
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options){}

public virtual DbSet<IdentityUser> BOAPUser {  get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{base.OnModelCreating(modelBuilder);}

Startup.cs 具有:

services.AddDefaultIdentity<BOAPUser>(options => options.SignIn.RequireConfirmedAccount = false)
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>();

与它破裂的地方:

using (var scope = app.ApplicationServices.CreateScope())
{
var userManager = scope.ServiceProvider.GetRequiredService<UserManager<IdentityUser>>();
asp.net asp.net-core-mvc asp.net-identity

评论


答:

1赞 RJPWilliams 11/15/2023 #1

我找到了问题所在。导致问题的行应为

var userManager = scope.ServiceProvider.GetService<UserManager<ApplicationUser>>();

而不是

var userManager = scope.ServiceProvider.GetService<UserManager<IdentityUser>>();