Using AutoMapper to Map Abstract Classes<!-- --> | <!-- -->Patrick Desjardins Blog
Patrick Desjardins Blog
Patrick Desjardins picture from a conference

Using AutoMapper to Map Abstract Classes

Posted on: March 20, 2014

AutoMapper lets you map from one class to another class your object. It works fine until you want to map from a class to an abstract class. The reason is that AutoMapper instantiates the desired class type and since an abstract class cannot be instantiate will crash.

1//Mapping Mapper.CreateMap<SelectorItem, OrderType>() //Use the mapping var model = AutoMapper.Mapper.Map<SelectorItem, OrderType>(viewModel);

The code create the map from SelectorItem that is a normal class and OrderType that is an abstract class. The use of this map will not work. To fix this problem the mapping configuration must be changed to specify to AutoMapper how to instantiate the OrderType class, the abstract class.

1Mapper.CreateMap<SelectorItem, OrderType>() .ConstructUsing(OrderTypeCreator);

The mapping requires the use of ConstructUsing method that has two signatures.

1IMappingExpression<TSource, TDestination> ConstructUsing(Func<TSource, TDestination> ctor); IMappingExpression<TSource, TDestination> ConstructUsing(Func<ResolutionContext, TDestination> ctor);

The first one is easy to use. It takes a method that has the source which is the class we start with and return a destination class that is the abstract class.

1private OrderType OrderTypeCreator(SelectorItem arg) { return OrderType.GetFromId(arg.Id); }

This example takes from the concrete class the ID and use a factory to return the correct concrete class that inherit form the abstract OrderType class.

This way, we have AutoMapper that can map to abstract Class without problem.