我最终创建了一个新的映射器实例并将它们缓存在共享(静态)并发字典中。
这是我的代码(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