ASP.NET Core 3.1集成Identity后报错无法解析AutoMapper.IConfiguration服务
报错信息
System.AggregateException: 'Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: Services.Contracts.IServiceManager Lifetime: Scoped ImplementationType: Service.ServiceManager': Unable to resolve service for type 'AutoMapper.Configuration.IConfiguration' while attempting to activate 'Service.ServiceManager'.)'
InvalidOperationException: Unable to resolve service for type 'AutoMapper.Configuration.IConfiguration' while attempting to activate 'Service.ServiceManager'.
问题根因
报错本质是ASP.NET Core依赖注入容器无法为Service.ServiceManager类提供它构造函数声明需要的AutoMapper.Configuration.IConfiguration实例,常见触发原因有两个:
- 命名空间引用错误:将ASP.NET Core自带的配置接口
Microsoft.Extensions.Configuration.IConfiguration和AutoMapper的配置接口AutoMapper.Configuration.IConfiguration混淆,在ServiceManager构造函数中错误引用了AutoMapper的IConfiguration - AutoMapper服务未正确注册:确实需要使用AutoMapper配置能力,但未将AutoMapper相关服务注入到DI容器中
修复步骤
- 优先检查
ServiceManager类的构造函数的IConfiguration引用命名空间:如果你的需求是注入项目全局配置(比如appsettings.json中的配置项),将引用改为using Microsoft.Extensions.Configuration;,删除using AutoMapper.Configuration;即可解决90%以上的该类报错 - 如果确实需要在
ServiceManager中使用AutoMapper的配置能力,先确保已安装AutoMapper.Extensions.Microsoft.DependencyInjectionNuGet包,再在Startup.cs的ConfigureServices方法中添加AutoMapper服务注册:// 参数替换为你存放AutoMapper Profile配置类的程序集即可 services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); - 推荐
ServiceManager中如果需要使用AutoMapper的映射能力,直接注入IMapper接口而非AutoMapper的配置类,构造函数示例:public ServiceManager(IRepositoryManager repositoryManager, IMapper mapper, Microsoft.Extensions.Configuration.IConfiguration configuration) { // 初始化逻辑 } - 如果你是在集成Identity过程中出现的该报错,检查服务注册顺序:将AutoMapper的注册逻辑放在Identity服务注册逻辑之前,避免注入覆盖
内容的提问来源于stack exchange,提问作者itz4blitz
相关产品推荐
相关产品推荐

