Automapper - CreateMap called multiple times

血红的双手。 提交于 2019-12-08 15:12:54

问题


What happens when I call Mapper.CreateMap with the same types multiple times?

Does it rewrite the previous map? If so, is it possible to make it throw an exception if I try to create map, that is already created?


回答1:


When calling Mapper.CreateMap for the same set of source and destination several times, nothing will happen at all as the Mapper.CreateMap<TSource, TDestination>() does not set up any extensions for a mapping configuration. If you set the overrides for IMappingExpression like this Mapper.CreateMap<TSource, TDestination>().ConstructUsing(x=>new TDestination(x.SomeField)), than yes, the configuration for this mapping will be replaced with the new one. Regarding the second part of your question, I know the way to verify if the map was already created:

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);
}


来源:https://stackoverflow.com/questions/6355381/automapper-createmap-called-multiple-times

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!