是Mapper.Map在AutoMapper线程安全的? [英] Is Mapper.Map in AutoMapper thread-safe?

查看:663
本文介绍了是Mapper.Map在AutoMapper线程安全的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在找了 AutoMapper $ C $现在C(评估它为我的工作项目之一),而且,坦白说,我很惊讶:

I'm looking up AutoMapper code now (evaluating it for one of projects I'm working on), and, frankly speaking, I'm quite surprised:

  • 在该库的API是基于一个静态的接入点(映射键入),所以一般它的任何方法必须是线程安全
  • 但我没有发现这code的任何证据。
  • The library API is based on a single static access point (Mapper type), so generally any of its methods must be thread safe
  • But I didn't find ANY evidence of this in code.

所有我能找到是这个问题,但即使是言言似乎有不正确的:如果地图并没有在内部使用线程安全的数据结构,它不能被认为是线程安全的为好,如果我要打电话 CreateMap 在非并发环境,但同时具有地图

All I was able to find is this issue, but even the statement made there seems incorrect: if Map doesn't use thread-safe data structures internally, it can't be considered as thread-safe as well, if I'm going to call CreateMap in non-concurrent context, but concurrently with Map.

即。 AutoMapper在例如唯一可能的使用模式ASP.NET MVC应用程序是:

I.e. the only possible usage pattern of AutoMapper in e.g. ASP.NET MVC application is:

lock (mapperLock) {
    ... Mapper.AnyMethod(...) ...
}

显然,如果我是正确的,这是一个巨大的缺乏。

Obviously, if I'm correct, that's a huge lack.

所以,我有两个问题:

  • 对吗?
  • 如果是,什么是AutoMapper的最佳替代品,不存在此问题

推荐答案

该链接 的问题或多或少回答你的问题:

The linked issue more or less answers your questions:

Mapper.CreateMap不是线程安全的,也永远是。然而,   Mapper.Map是线程安全的。映射器静态类只是一个薄   包装上的MappingEngine和配置对象之上。

Mapper.CreateMap is not threadsafe, nor will it ever be. However, Mapper.Map is thread-safe. The Mapper static class is just a thin wrapper on top of the MappingEngine and Configuration objects.

因此​​,只有使用 Mapper.CreateMap 如果你做你的配置中的一个集中的地方在一个线程安全的方式。

So only use Mapper.CreateMap if you do your configuration in one central place in a threadsafe manner.

您的评论是:

我问,是因为我想配置automatter就地,   即使用之前。我打算把它配置在非并发   情况下,即〜锁(mapperConfigLock){Mapper.CreateMap()......; },   我担心这是不够的了。

I'm asking this because I'd like to configure automatter in-place, i.e. right before usage. I planned to configure it in non-concurrent context, i.e. ~ lock (mapperConfigLock) { Mapper.CreateMap()....; }, and I fear this is not enough now.

如果你正在做的就地配置只是不使用静态映射类。随着对GitHub的问题上意见建议直接使用映射引擎:

If you are doing in-place configuration just don't use the static Mapper class. As the comment on the github issue suggest use the mapping engine directly:

var config = 
    new ConfigurationStore(new TypeMapFactory(), MapperRegistry.AllMappers());
config.CreateMap<Source, Destination>();
var engine = new MappingEngine(config);

var source = new Source();
var dest = engine.Map(source);

这是更code一点点,但你可以围绕它创建自己的助手。 但一切都在当地一个给定的方法,所以没有共享的状态,无需担心线程安全。

It's a little bit of more code but you can create your own helpers around it. But everything is local in a given method so no shared state no need to worry about thread safety.

这篇关于是Mapper.Map在AutoMapper线程安全的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆