How to switch to "this" using AutoMapper in the constructor

I have a source type that has properties and a destination type that have exactly the same properties.

After I configured one simple mapping for AutoMapper, for example:

Mapper.CreateMap<MySourceType, MyDestinationType>();

I would like to have a MyDestinationType constructor that has a MySourceType parameter, then automatically initialize the type properties when created using the source as follows:

public MyDestinationType(MySourceType source)
{
    // Now here I am do not know what to write.
}

The only workaround I found was to create a static factory method for

public static MyDestinationType Create(MySourceType source)
{
     return Mapper.Map<MyDestinationType>(source);
}

Is there any way to avoid this static ugliness?

+4
source share
1 answer

, :

public MyDestinationType(MySourceType source)
{
    Mapper.Map<MySourceType, MyDestinationType>(source, this);
}
+5

Source: https://habr.com/ru/post/1584275/


All Articles