【问题标题】:Telling injected automapper to use specific mapping profile in map function告诉注入的 automapper 在 map 函数中使用特定的映射配置文件
【发布时间】:2018-06-15 08:50:27
【问题描述】:

在某些情况下,我的一个应用程序服务必须为前端生成带有匿名数据的 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));

这可能吗?如果可以:怎么做?

【问题讨论】:

  • 根据我的经验,将 AutoMapper 作为依赖项注入是一个坏主意。特别是在这种情况下,很难判断发生了什么,即在运行时将创建哪种 DTO。我建议new使用所需配置在服务中设置映射器。

标签: c# automapper


【解决方案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");
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-23
    • 1970-01-01
    • 2021-09-30
    • 1970-01-01
    • 2011-01-12
    相关资源
    最近更新 更多