Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automapper - CreateMap called multiple times

Tags:

automapper

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?

like image 624
Euphoric Avatar asked Jun 15 '11 09:06

Euphoric


1 Answers

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);
}
like image 93
Arthur P Avatar answered Oct 23 '22 11:10

Arthur P