How to map to "this" with AutoMapper in constructor

2.5k views Asked by At

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

After I configure one simple mapping for AutoMapper like:

Mapper.CreateMap<MySourceType, MyDestinationType>();

I would like to have a constructor of MyDestinationType which have a MySourceType parameter, then automatically initialize properties of the type under creation with the source like this:

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

The only workaround I found is create a static factory method for

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

Is there any way to not to have this static ugliness?

2

There are 2 answers

0
Alex On BEST ANSWER

Although I personally find it ugly, what you can do is the following:

public MyDestinationType(MySourceType source)
{
    Mapper.Map<MySourceType, MyDestinationType>(source, this);
}
0
tno2007 On

I achieved this using:

public MyDestinationType(MySourceType source)
{
    var mapperConfiguration = new MapperConfiguration(cfg =>
    {
        cfg.CreateMap<MySourceType, MyDestinationType>();
    });

    var mapper = mapperConfiguration.CreateMapper();

    mapper.Map(source, this);
}