📜  asp.net 核心标识脚手架错误 (1)

📅  最后修改于: 2023-12-03 14:59:24.517000             🧑  作者: Mango

ASP.NET Core Identity Scaffold Error

介绍

ASP.NET Core Identity Scaffold 是一个用于创建认证和授权功能的脚手架工具。使用它可以快速地添加用户登录、注册、密码重置、角色管理等功能。然而在使用这个工具的过程中,可能会遇到各种错误。其中一个常见的错误是 "No parameterless constructor defined for this object",这个错误通常发生在生成 Identity 程序时。

常见错误
No parameterless constructor defined for this object

这个错误通常是由于无法实例化 Identity 服务的依赖项所导致的。为了解决这个问题,我们需要找出是哪个依赖项导致了问题,然后去修复它。常见的依赖项有:

  • ILoggerFactory
  • UserManager
  • SignInManager
  • RoleManager
  • IEmailSender
  • IPasswordHasher

要修复这个错误,我们需要先定位到错误发生的位置。一般情况下,错误信息中会包含堆栈跟踪信息,我们可以根据这些信息来确定错误发生的位置。

InvalidOperationException: No service for type 'XXX' has been registered

这个错误通常是由于依赖项未正确注入导致的。当你使用依赖注入来注入 Identity 服务和它们的依赖项时,如果依赖项未正确注册,就会出现这个错误。

要解决这个问题,需要确保 Identity 服务和它们的依赖项都已经正确地注册。你可以通过在 Startup.cs 文件中使用 services.AddIdentity() 方法来注册 Identity 服务。如果你有其他需要注入的依赖项,可以使用 services.AddScoped()、services.AddSingleton()、 services.AddTransient() 等方法进行注入。

InvalidOperationException: Unable to resolve service for type 'XXX' while attempting to activate 'YYY'

这个错误通常是由于依赖项未正确注入导致的。当你使用依赖注入来注入 Identity 服务和它们的依赖项时,如果依赖项的类型与所需类型不匹配,就会出现这个错误。

要解决这个问题,需要确保所需要的依赖项已经正确地注册并且类型匹配。你可以通过检查依赖项的类型和所需类型是否匹配来确定问题所在。如果不匹配,可以尝试更改依赖项的类型或更新所需类型来解决问题。

解决问题的方法

解决问题的方法主要有两种:

  1. 阅读错误信息和堆栈跟踪信息,了解错误发生的原因和位置,并进行相应的修复。

  2. 使用 Identity 核心源代码进行调试,找到错误发生的位置并进行修复。

参考文献
代码片段
// 注册 Identity 服务
services.AddIdentity<ApplicationUser, IdentityRole>()
    .AddEntityFrameworkStores<ApplicationDbContext>()
    .AddDefaultTokenProviders();

// 注册其他依赖项
services.AddScoped<IEmailSender, EmailSender>();
services.AddTransient<IPasswordHasher<ApplicationUser>, PasswordHasher<ApplicationUser>>();
// 使用构造函数注入 Identity 服务和其他依赖项
public AccountController(UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager, IEmailSender emailSender)
{
    _userManager = userManager;
    _signInManager = signInManager;
    _emailSender = emailSender;
}