I am having an issue using AutoMapper (which is an excellent technology) to map a business object to a DTO where I have inheritance off of an abstract base class within a co
Building on Olivier's response, I could not get his to work in my context... it kept going in an infinite loop and threw a StackOverflowException.
In this example, AbstractClass is my base class and AbstractViewModel is my base view model (not marked as abstract mind you).
However, I did get it to work using this hackish looking converter:
public class ProxyConverter : ITypeConverter
where TSource : class
where TDestination : class
{
public TDestination Convert(ResolutionContext context)
{
// Get dynamic proxy base type
var baseType = context.SourceValue.GetType().BaseType;
// Return regular map if base type == Abstract base type
if (baseType == typeof(TSource))
baseType = context.SourceValue.GetType();
// Look up map for base type
var destType = (from maps in Mapper.GetAllTypeMaps()
where maps.SourceType == baseType
select maps).FirstOrDefault().DestinationType;
return Mapper.DynamicMap(context.SourceValue, baseType, destType) as TDestination;
}
}
// Usage
Mapper.CreateMap()
.ConvertUsing(new ProxyConverter());
So, a DerivedClassA will map normally, but a DynamicProxy_xxx will also map properly as this code inspects its base type (DerivedClassA).
Please, please, please show me that I don't have to do this crazy lookup crap. I don't know enough AutoMapper to fix Olivier's answer properly.