告诉注入的自动映射器在映射函数中使用特定的映射配置文件



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

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

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

这是否可能,如果是:如何?

据我所知,当您拨打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");
}

最新更新