首页 文章

告诉注入的automapper在 Map 功能中使用特定的映射配置文件

提问于
浏览
0

在某些情况下,我的一个应用程序服务必须为前端生成带有匿名数据的DTO . 我们的想法是使用不同的AutoMapper配置文件将域对象映射到DTO,并映射所有属性或匿名DTO . 我生成了这两个配置文件并将它们注入服务中 . AutoMapper也作为 IMapper 注入服务,并包含应用程序的所有映射配置文件 .

我现在需要的是告诉映射器在Map函数的调用中使用一个特定的配置文件 . 像这样的东西:

var anonymizedDto = _autoMapper.Map<SourceType, DestinationType> 
    (sourceObject, ops => ops.UseMappingProfile(_anonymizedMapingProfile));

var normalDto = _autoMapper.Map<SourceType, DestinationType>
    (sourceObject, ops => ops.UseMappingProfile(_normalMappingProfile));

这是可能的,如果是的话:怎么样?

1 回答

  • 1

    据我所知,当您调用 Map 时,无法更改配置文件 .

    您可以做的是注入两个配置了不同配置文件的映射器 .

    public class MyService : IService {
    
       private readonly IMappingEngine _defaultMapper;
       private readonly IMappingEngine _anonymousMapper;
    
       public MyService(IMappingEngine defaultMapper, IMappingEngine anonymousMapper) {
           _defaultMapper = defaultMapper;
           _anonymousMapper = anonymousMapper;
       }
    
       public MyDto GetDefault() {
           return _defaultMapper.Map<MyDto>(sourceObject);
       }
    
       public MyDto GetAnonymous() {
           return _anonymousMapper.Map<MyDto>(sourceObject);
       }
    }
    

    在依赖项容器中,设置构造函数注入以遵守ctor参数的名称 . 例如StructureMap

    public void ConfigureAutoMappers(ConfigurationExpression x) {
    
        // register default mapper (static mapping configuration)
        Mapper.Configuration.ConstructServicesUsing(t => container.GetInstance(t));
        Mapper.Configuration.AddProfile<DefaultProfile>();
        var defaultAutomapper = Mapper.Engine
        x.For<IMappingEngine>().Use(() => defaultAutoMapper).Named("DefaultAutoMapper");
    
        // register anonymous mapper
        var anonConfig = new AnonConfigurationStore( // class derived from ConfigurationStore
            new TypeMapFactory(), 
            AutoMapper.Mappers.MapperRegistry.AllMappers()
        ); 
        anonConfig.ConstructServicesUsing(container.GetInstance);
        var anonAutoMapper = new MappingEngine(anonConfig);
        x.For<IMappingEngine>().Add(anonAutoMapper).Named("AnonAutoMapper");
    
        // Inject the two different mappers into our service
        x.For<IService>().Use<MyService>()
            .Ctor<IMappingEngine>("defaultMapper").Named("DefaultAutoMapper")
            .Ctor<IMappingEngine>("anonymousMapper").Named("AnonAutoMapper");
    }
    

相关问题