I need to create a maping (using AutoMapper) from n classes all being derived from one abstract class to a contract class
So for example:
public abstract class bar
{
public string Field1 {get; set;}
public someClass Field2 {get; set;}
}
public class foo1bar: bar
{
// members
}
public class foo2bar: bar
{
// members
}
public class barContract
{
public string Field1 {get; set;}
// this will use existing someClass.Description field
public string Field2Description {get; set;}
}
implementations of bar class are multiple, and also are likely to change (more will be added) As Automapper cannot map to abstract class (so the construct mapperConfiguration.CreateMap<bar, barContract>()
is incorrect), I was wondering will it be possible to use reflection to find all classes 'implementing' bar class and map them 'automatically'
var type = typeof(bar);
var types = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(s => s.GetTypes())
.Where(p => type.IsAssignableFrom(p));
I've got the Types, and I'm trying to invoke CreateMap. As the type is now a variable, im creating a generic method once again using refelction:
foreach (Type t in types)
{
mapperConfiguration.GetType().GetMethod("CreateMap")
.MakeGenericMethod(t, typeof(barContract))
.Invoke(mapperConfiguration, null);
}
the problem is that CreateMap is not a member of type that is extracted from mapperconfiguration instance - when im tryng to extract the method by name i get null. I see its defined in IProfileExpression, so I'm trying to extract the method from the interface: typeof(IProfileExpression).GetMethod("CreateMap")
and i get System.Reflection.AmbiguousMatchException - what is kind of ok, but using System.Reflection.BindingFlags in GetMethod to be more specyfic I'm again getting nulls.
What am I doing wrong, or how to get around that mapping problem ?
Aucun commentaire:
Enregistrer un commentaire