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

在AutoMapper Mapping Profile中注入服务时遇映射配置缺失错误

AutoMapper注入服务后出现映射配置缺失问题

原正常运行配置

Startup.cs

public static IServiceCollection AddServices(this IServiceCollection serviceCollection, IConfiguration configuration)
{
    serviceCollection.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
}

映射配置类(MappingProfile)

public class MyDtoMappingProfile: Profile
{
    public MyDtoMappingProfile()
    {
        CreateMap<MyDtoMappingSource<MyContentType>, MyDestinationObject>()
            .ForMember(d => d.BatchFeedDate, opt => opt.MapFrom(s => DateTime.UtcNow));
    }
}

修改后的配置(尝试注入ILookupCodeMapper)

为了在映射配置中使用ILookupCodeMapper服务,修改了如下代码:

Startup.cs

public static IServiceCollection AddServices(this IServiceCollection serviceCollection, IConfiguration configuration)
{
    serviceCollection.AddAutoMapper(builder => {
        builder.AddProfile(new MyDtoMappingProfile(serviceCollection.BuildServiceProvider().GetService<ILookupCodeMapper>()));
    });
}

映射配置类(MappingProfile)

public class MyDtoMappingProfile: Profile
{
    private readonly ILookupCodeMapper lookupCodeMapper;

    public MyDtoMappingProfile(ILookupCodeMapper lookupCodeMapper)
    {
        this.lookupCodeMapper = lookupCodeMapper;

        CreateMap<MyDtoMappingSource<MyContentType>, MyDestinationObject>()
            .ForMember(d => d.BatchFeedDate, opt => opt.MapFrom(s => DateTime.UtcNow))
            .ForMember(d => d.Strand, opt => opt.MapFrom(s => lookupCodeMapper.Code(s.StringValue)));
    }
}

出现的错误

缺少类型映射配置或不支持的映射。

解决方法

问题根源在于手动实例化MyDtoMappingProfile时调用了serviceCollection.BuildServiceProvider(),这会创建独立的服务容器实例,可能导致依赖未正确初始化,同时覆盖了AutoMapper自动扫描Profile的逻辑。正确做法是让AutoMapper自动加载Profile并通过依赖注入解析构造函数参数:

  1. 修正Startup.cs配置
    先确保ILookupCodeMapper已注册到服务容器,再让AutoMapper自动扫描程序集加载所有Profile:
public static IServiceCollection AddServices(this IServiceCollection serviceCollection, IConfiguration configuration)
{
    // 注册ILookupCodeMapper的实现类
    serviceCollection.AddScoped<ILookupCodeMapper, LookupCodeMapper>();

    // 自动扫描程序集并加载所有Profile,包括带构造函数依赖的
    serviceCollection.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
}
  1. 映射配置类保持不变
    你的MyDtoMappingProfile构造函数注入ILookupCodeMapper的写法是正确的,无需修改。

核心原因说明

  • serviceCollection.BuildServiceProvider()会创建新的服务提供者,此时部分服务可能未完成注册,导致获取的ILookupCodeMapper实例异常,进而破坏映射配置。
  • AddAutoMapper原生支持扫描程序集中的所有Profile类型,并通过依赖注入容器自动解析Profile的构造函数依赖,无需手动实例化。

内容的提问来源于stack exchange,提问作者O'Neil Tomlinson

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 02:54:24