【发布时间】:2017-11-17 14:10:45
【问题描述】:
我们在 ASP.NET Core 2.0 中使用自动映射器。
我们喜欢创建一次映射配置,每个映射器都会使用该配置。我们为每个请求创建一个映射器,我们不会遇到问题,因为我读过一次 automapper 不是线程安全的。
我们喜欢在应用程序启动时预编译映射配置(参见 Code MapperConfigruation.CompileMappings();
如果我测量映射花费的时间,我发现第一个映射比其他映射需要更多时间。这是有原因的还是我有错误?
代码
在 Startup 类的 ConfigureService 中:
services.AddSingleton<MyMapperConfiguration>();
services.AddScoped<IObjectMapper, MyMapper>();
映射器配置
public class MyMapperConfiguration
{
public MapperConfiguration MapperConfiguration { get; private set; }
public MappingDefinition MappingDefinition { get; }
public MapperConfiguration(IOptions<MappingDefinition> mappings)
{
// MappingDefinitions hold some information where to search mappings
MappingDefinition = mappings.Value;
}
public void Configure()
{
List<Type> mappingDefinitionClasses = new List<Type>();
// Search Types with special attribute and add it to the typelist
MapperConfiguration = new MapperConfiguration(cfg =>
{
cfg.AddProfiles(mappingDefinitionClasses.ToArray());
});
MapperConfiguration.CompileMappings(); // <-- THIS SHOULD COMPILE THE MAPPING I THNIK?!
}
`
映射器
public class MyMapper : IObjectMapper
{
public IMapper Mapper { get; }
public Mapper(MapperConfiguration mappingConfiguration)
{
Mapper = mappingConfiguration.MapperConfiguration.CreateMapper();
}
public TDestination Map<TSource, TDestination>(TSource source)
{
return Mapper.Map<TSource, TDestination>(source);
}
}
IObjectMapper:
public interface IObjectMapper
{
TDestination Map<TSource, TDestination>(TSource source);
}
在 webApi 中测量时间
Stopwatch sw = new Stopwatch();
sw.Start();
destObj = _mapper.Map<Source, Destination>(sourceObj);
sw.Stop();
Debug.WriteLine($"Duration of mapping: {sw.ElapsedMilliseconds}");
在 Startup 的 Configrate 方法中,我还获得了映射配置的实例,并调用了该实例存在的 Configure()。
【问题讨论】:
-
您应该查看用于 AutoMapper 的 ASP.NET Core 的扩展包:github.com/AutoMapper/…,这使得设置变得更加容易。
-
我们不喜欢直接依赖自动映射器。应该可以交换映射器实现
-
什么?为什么?那将是一项没有太多好处的工作。如果你想改变映射器的实现,不要抽象,只要学习正则表达式。
-
正则表达式和映射?
-
主要目标是有可能在一个地方交换映射器实现。
标签: c# automapper asp.net-core-2.0