11

我有两个实体:Order & OrderDTO我正在使用AutoMapper将它们映射在一起。

根据某些条件,我希望这些实体以不同的方式映射

事实上,我希望这些实体有两个或更多不同的映射规则( CreateMap)。

当调用Map函数时,我想告诉引擎使用哪个映射规则

感谢这个问题:Using the instance version of CreateMap and Map with a WCF service? 一种方法是使用不同的映射器实例,因此每个实例都可以拥有自己的映射规则:

var configuration = new ConfigurationStore(new TypeMapFactory(), MapperRegistry.AllMappers());
var mapper = new MappingEngine(configuration);
configuration.CreateMap<Dto.Ticket, Entities.Ticket>()

你有更好的解决方案吗?

正如Jimmy Bogard(AutoMapper 的创建者)在这里提到的:Using Profiles in Automapper to map the same types with different logic

您最好创建单独的配置对象,并为每个对象创建一个单独的 MappingEngine。Mapper 类只是其中每一个的静态外观,具有一些生命周期管理。

需要进行哪些生命周期管理?

4

2 回答 2

3

我最终创建了一个新的映射器实例并将它们缓存在共享(静态)并发字典中。

这是我的代码(vb.net):

映射器工厂:

Public Function CreateMapper() As IMapper Implements IMapperFactory.CreateMapper
            Dim nestedConfig = New ConfigurationStore(New TypeMapFactory, MapperRegistry.Mappers)
            Dim nestedMapper = New MappingEngine(nestedConfig)
            Return New AutomapperMapper(nestedConfig, nestedMapper)
 End Function

针对不同场景的不同配置文件:

Private Shared _mapperInstances As New Concurrent.ConcurrentDictionary(Of String, IMapper)

Public Shared ReadOnly Property Profile(profileName As String) As IMapper
            Get
                Return _mapperInstances.GetOrAdd(profileName, Function() _mapperFactory.CreateMapper)
            End Get
End Property

和映射器类:

Friend Class AutomapperMapper
        Implements IMapper

        Private _configuration As ConfigurationStore
        Private _mapper As MappingEngine

        Public Sub New()
            _configuration = AutoMapper.Mapper.Configuration
            _mapper = AutoMapper.Mapper.Engine
        End Sub

        Public Sub New(configuration As ConfigurationStore, mapper As MappingEngine)
            _configuration = configuration
            _mapper = mapper
        End Sub

        Public Sub CreateMap(Of TSource, TDestination)() Implements IMapper.CreateMap
            _configuration.CreateMap(Of TSource, TDestination)()
        End Sub

        Public Function Map(Of TSource, TDestination)(source As TSource, destination As TDestination) As TDestination Implements IMapper.Map
            Return _mapper.Map(Of TSource, TDestination)(source, destination)
        End Function

        Public Function Map(Of TSource, TDestination)(source As TSource) As TDestination Implements IMapper.Map
            Return _mapper.Map(Of TSource, TDestination)(source)
        End Function


    End Class
于 2014-06-10T22:31:08.540 回答
2

遇到同样的问题,发现一个月前AutoMapper升级到4.2.0,开始支持不同配置创建的instance mapper,静态mapper功能被标记为废弃。所以以后我们不需要自己去实现了!

于 2016-02-16T13:34:08.370 回答