igorGIS
igorGIS

Reputation: 1956

How to initialize Automapper when source type is unknown

I have following code:

public static TDest Map2<TDest>(this object sourceObjInstance) where TDest : new()
{
    var itemType = typeof(TDest);
    var item = Activator.CreateInstance(itemType);
    Mapper.Initialize((cfg => cfg.CreateMap<??????, TDest>());
    var result = Mapper.Map(sourceObjInstance, item, sourceObjInstance.GetType(), item.GetType());
    return (TDest)result;
}

So, I don't know where to get generic parameter (????? placeholder) for source object for mapper.initialize method. The sourceObjInstance will be autogenerated class by WCF.

Upvotes: 1

Views: 595

Answers (1)

Ilya Chumakov
Ilya Chumakov

Reputation: 25019

Automapper supports dynamic mapping. Set CreateMissingTypeMaps configuration property when you don't know the source/destination type at compile time:

Mapper.Initialize(cfg => cfg.CreateMissingTypeMaps = true);

object src = new Src();
object dest = new Dest();

Mapper.Map(src, dest);

Upvotes: 1

Related Questions