.NET 8中未注册UserManager<ApplicationUser>服务的问题求助
解决"No service for type 'Microsoft.AspNetCore.Identity.UserManager`1[Areas.Identity.Data.ApplicationUser]' has been registered."错误
错误原因
你在Program.cs中注册身份服务时,指定的是默认的IdentityUser类型,但实际项目中使用了自定义的ApplicationUser类,并且在视图里注入的是UserManager<ApplicationUser>和SignInManager<ApplicationUser>。依赖注入容器只能找到UserManager<IdentityUser>的注册实例,无法匹配你请求的ApplicationUser版本,因此抛出该错误。
解决步骤
修正Program.cs中的服务注册
将AddDefaultIdentity<IdentityUser>替换为AddDefaultIdentity<ApplicationUser>,让身份服务基于你的自定义用户类:builder.Services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = false) .AddRoles<IdentityRole>() .AddEntityFrameworkStores<ApplicationDbContext>();确保ApplicationDbContext正确关联自定义用户
检查你的ApplicationDbContext是否继承自IdentityDbContext<ApplicationUser>,而非默认的IdentityDbContext,这样EF Core才能正确处理自定义用户的数据库映射:public class ApplicationDbContext : IdentityDbContext<ApplicationUser> { public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { } // 项目中其他DbSet定义 }清理并重新生成项目
执行清理解决方案(Clean Solution)和重新生成(Rebuild Solution)操作,确保所有代码变更生效,依赖注入容器能正确识别注册的服务类型。
内容的提问来源于stack exchange,提问作者bee
相关产品推荐
相关产品推荐

