当我多次调用相同类型的Mapper.CreateMap时会发生什么?

是否重写了以前的 map ?如果是这样,如果我尝试创建已经创建的 map ,是否有可能引发异常?

最佳答案

多次为同一组源和目标调用Mapper.CreateMap时,什么都不会发生,因为Mapper.CreateMap<TSource, TDestination>()没有为映射配置设置任何扩展名。
如果您像这样设置IMappingExpression的替代Mapper.CreateMap<TSource, TDestination>().ConstructUsing(x=>new TDestination(x.SomeField))
是的,此映射的配置将替换为新的配置。
关于问题的第二部分,我知道验证 map 是否已创建的方法:

public TDestination Resolve<TSource, TDestination>(TSource source)
{
     var mapped = Mapper.FindTypeMapFor(typeof(TSource), typeof(TDestination)); //this will give you a reference to existing mapping if it was created or NULL if not

     if (mapped == null)
     {
        var expression = Mapper.CreateMap<TSource, TDestination>();
     }
     return Mapper.Map<TSource, TDestination>(source);
}

关于Automapper-多次调用CreateMap,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6355381/

10-11 22:29
查看更多