【问题标题】:Automapper Compile MappingsAutomapper 编译映射
【发布时间】: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


【解决方案1】:

AM 是线程安全的。映射器本身并不昂贵,您可以分享或不分享。它确实分配了一些东西,所以如果可以的话,分享它会更便宜。 CompileMappings 有点改变,所以升级到最新的。但除此之外,它可能是您看到的 JIT 编译器。在执行映射之前,代码不会被编译。 CompileMappings 只是将表达式编译为 IL。 JIT 将 IL 编译为机器码。您可以分析并验证发生的情况。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-26
    • 2014-06-30
    • 1970-01-01
    • 2020-07-17
    • 2012-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多