Afs*_* Gh 10 .net c# asp.net asp.net-mvc automapper
我有两个实体:Order&OrderDTO我正在使用AutoMapper将它们映射在一起.
基于某些条件,我希望这些实体的映射方式不同.
实际上,我想为这些实体提供两个或更多不同的映射规则(CreateMap).
并且在调用Map函数时我想告诉引擎使用哪个映射规则.
感谢这个问题:使用CreateMap的实例版本和使用WCF服务映射?一种方法是使用不同的mapper实例,因此每个实例都可以拥有自己的映射规则:
var configuration = new ConfigurationStore(new TypeMapFactory(), MapperRegistry.AllMappers());
var mapper = new MappingEngine(configuration);
configuration.CreateMap<Dto.Ticket, Entities.Ticket>()
Run Code Online (Sandbox Code Playgroud)
你有更好的解决方案吗?
正如Jimmy Bogard(AutoMapper的创建者)所说:在Automapper中使用Profiles来映射具有不同逻辑的相同类型:
您最好创建单独的Configuration对象,并为每个对象创建单独的MappingEngine.Mapper类只是每个上面的静态外观,带有一些生命周期管理.
需要完成哪些生命周期管理?
我最终创建了一个新的映射器实例并将它们缓存在共享(静态)并发字典中。
这是我的代码(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
Run Code Online (Sandbox Code Playgroud)
不同的场景有不同的配置文件:
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
Run Code Online (Sandbox Code Playgroud)
和映射器类:
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3816 次 |
| 最近记录: |