AutoMapper中相同实体类型的不同映射规则

时间:2013-06-08 02:33:27

标签: c# asp.net .net asp.net-mvc automapper

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

基于某些条件,我希望这些实体以不同方式映射

事实上,对于这些实体,我需要两个或更多不同的映射规则CreateMap)。

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

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

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

  

最好创建单独的Configuration对象,并且   为每个人创建一个单独的MappingEngine。 Mapper类只是   一个静态的外观,每个都有一些生命周期管理。

需要完成哪些生命周期管理?

2 个答案:

答案 0 :(得分:3)

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

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

mapper factory:

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

和mapper类:

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

答案 1 :(得分:1)

我遇到了同样的问题,我发现AutoMapper一个月前升级到4.2.0,由不同的配置开始support instances mappers,静态映射器功能被标记为已过时。所以我们从现在开始不需要自己实施!