【发布时间】:2013-12-03 18:31:17
【问题描述】:
我正在维护一个使用 AutoMapper 的应用,如下所示:
public class UserDomainService
{
public UserDTO GetUser(int id)
{
Mapper.Reset();
Mapper.CreateMap<User, UserDTO>();
var user = ....;
return Mapper.Map<User, UserDTO>(user);
}
}
此域服务由网络服务使用。
我认为当两个 Web 服务请求进入并在不同的线程上调用 Reset 和 Map 时可能会出现问题。
Mapper 可能会进入 Map() 失败的状态。
我知道我可能应该在 Application_Start 中设置 CreateMap() 映射,但现在我正在尝试这样做:
public class UserDomainService
{
public UserDTO GetUser(int id)
{
var config = new AutoMapper.Configuration(new TypeMapFactory(), MapperRegistry.AllMappers());
config.CreateMap<User, UserDTO>();
var mapper = new MappingEngine(configuration);
var user = ....;
return mapper.Map<User, UserDTO>(user);
}
}
抛开性能不谈,是否有任何可能导致应用崩溃的因素? 有时我会遇到这样的异常:
System.ArgumentException: An item with the same key has already been added.
at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource)
at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
at System.Collections.Generic.Dictionary`2.Add(TKey key, TValue value)
at AutoMapper.TypeMapFactory.GetTypeInfo(Type type)
at AutoMapper.TypeMapFactory.CreateTypeMap(Type sourceType, Type destinationType, IMappingOptions options)
at AutoMapper.Configuration.CreateTypeMap(Type source, Type destination, String profileName)
at AutoMapper.Configuration.CreateMap[TSource,TDestination](String profileName)
at AutoMapper.Configuration.CreateMap[TSource,TDestination]()
请注意,以上示例映射只是一个示例。
我在 3.5 Net 应用程序中使用 AutoMapper v1.1.0.188。
编辑: 我将配置放在 Application_Start 中并不容易,这是有特定原因的。 根据上下文,我有不同的映射要求。例如,对于同一个 User 到 UserDTO,我需要两种不同类型的映射。
这与这个老问题中描述的问题相同:
【问题讨论】:
-
正如你已经说过的: Mapper.Reset() 和 Mapper.CreateMap() 应该执行一次(例如在启动期间)。
-
谢谢,但这并没有多大帮助。你能解释一下为什么实例化 MappingEngine 不起作用吗?我需要知道为什么这不起作用。
标签: automapper