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

ASP.NET Core依赖注入中如何解析自定义IdentityErrorDescriber?

问题分析与解决方案

问题原因

AddErrorDescriber<CustomIdentityErrorDescriber>() 仅将自定义错误描述器注册为**基类型IdentityErrorDescriber**的实现,并未在DI容器中单独注册CustomIdentityErrorDescriber类型本身。因此直接在构造函数中请求CustomIdentityErrorDescriber时,容器找不到对应服务注册,抛出解析异常;而请求基类型时,容器会返回已注册的自定义实例,这就是用IdentityErrorDescriber能正常工作的原因。

解决方法

有两种方式支持直接注入自定义类型:

方法1:单独注册自定义类型

在Identity配置完成后,手动将CustomIdentityErrorDescriber注册到DI容器,保持与Identity一致的Scoped作用域:

services
  .AddIdentityCore<CustomUser>()
  .AddErrorDescriber<CustomIdentityErrorDescriber>()
  // ...其他Identity配置项

// 单独注册自定义错误描述器类型
services.AddScoped<CustomIdentityErrorDescriber>();

方法2:注册类型映射(共享实例)

如果希望自定义类型与基类型复用同一个实例,可通过以下方式注册,让容器请求CustomIdentityErrorDescriber时返回基类型对应的自定义实例:

services
  .AddIdentityCore<CustomUser>()
  // 注册基类型到自定义类型的映射
  .AddScoped<IdentityErrorDescriber, CustomIdentityErrorDescriber>()
  // ...其他Identity配置项

// 注册自定义类型的解析逻辑,复用基类型实例
services.AddScoped<CustomIdentityErrorDescriber>(sp => 
  sp.GetRequiredService<IdentityErrorDescriber>() as CustomIdentityErrorDescriber);

额外说明

无需注销默认的IdentityErrorDescriber实现,AddErrorDescriber<T>已经自动替换了基类型的服务注册,容器中只会存在你的自定义实例。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 15:39:58