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

Automapper是否支持映射带有依赖注入构造函数的类?

AutoMapper支持映射到带DI参数的构造函数吗?

AutoMapper确实支持这种场景,但默认情况下它会优先选择参数最少的构造函数(也就是你的无参构造),所以需要显式配置让它使用带依赖注入参数的构造。

解决步骤:

  1. 确保依赖已注册到DI容器
    先把IWantToBeInjected接口及其实现类注册到你的DI容器中,比如ASP.NET Core里:

    services.AddScoped<IWantToBeInjected, WantToBeInjectedImpl>();
    
  2. 修改映射配置,指定使用服务定位器构造对象
    在你的MappingProfile中,给映射规则添加ConstructUsingServiceLocator()配置,让AutoMapper从DI容器中解析构造所需的依赖:

    public class MappingProfile : AutoMapper.Profile
    {
        public MappingProfile()
        {
            CreateMap<BOLike, BO>()
                .ConstructUsingServiceLocator(); // 启用从DI容器获取构造依赖
        }
    }
    
  3. 确保IMapper正确注册到DI
    要让AutoMapper能访问到DI容器,必须通过官方扩展方法注册IMapper,比如ASP.NET Core中:

    services.AddAutoMapper(typeof(MappingProfile));
    

另一种显式构造的方式

如果需要更精细的控制,可以直接在Mapper配置中手动解析依赖:

var mapperConfig = new MapperConfiguration(cfg =>
{
    cfg.AddProfile<MappingProfile>();
    cfg.ConstructUsing((type, context) =>
    {
        if (type == typeof(BO))
        {
            var diDependency = context.Services.GetRequiredService<IWantToBeInjected>();
            return new BO(diDependency);
        }
        // 其他类型默认用DI容器解析或反射构造
        return context.Services.GetService(type) ?? Activator.CreateInstance(type);
    });
});

这样配置后,AutoMapper在映射BOLike到BO时,就会调用带IWantToBeInjected参数的构造函数,并自动从DI容器中获取该依赖实例。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 14:12:41