In my application I need to do many mappings (Domain objects, DTOs, ViewModels etc.) between different pair of objects. I use AutoMapper
heavily for the purpose.
So I have a common Mapper class which has methods to map different objects. As Mappings are persisted in the application, I do all my CreateMap()
in the static constructor
so that the mappings are created only once and are ready by the time I might use them. The class looks like this
public class SomeMapper
{
static SomeMapper()
{
Mapper.CreateMap<SomeType1, SomeOtherType1>();
Mapper.CreateMap<SomeType2, SomeOtherType2>();
Mapper.CreateMap<SomeType3, SomeOtherType3>();
//...
}
public SomeOtherType1 MapSomeHierarchy1(SomeType1 source)
{ //... }
public SomeOtherType2 MapSomeHierarchy2(SomeType2 source)
{ //... }
}
Question 1: What can be a better way to create the mappings? (better in any way - performance, semantics, standard practices etc.)
Question 2: This code is also used in a Console
application. In a particular run, it'll not need all the mappings. So, rather than creating all the mappings eagerly, can I create the map at run time if it does not exist already? Something like
public SomeOtherTypeN MapSomeHierarchyN(SomeTypeN source)
{
if (!AlreadyMapped(SomeTypeN, SomeOtherTypeN))
Mapper.CreateMap<SomeTypeN, SomeOtherTypeN>();
return Mapper.Map<SomeOtherTypeN>(source);
}
Is there a simple way to implement the method AlreadyMapped()
?