Automapper - CreateMap called multiple times

2019-06-15 07:41发布

问题:

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


标签: AutoMapper