简体   繁体   中英

Automapper: using BeforeMap and AfterMap

I am using automapper (successfully up to a point) to perform a polymorphic map between two interfaces like so:

configure.CreateMap<IFrom, ITo>()
    .Include<FromImplementation1, ToImplementation1>()
    .Include<FromImplementation2, ToImplementation2>()
    ... ;

This works fine. In addition however, the interfaces include method signatures, the implementations of which are intended to modify the objects before mapping:

public interface IFrom
{
    void PrepareForMapping();
}

As you can see the method has no return but is designed to modify the state of the object before the mapping is performed. At present this method is called manually before the object is mapped, but my intention was to execute the method automatically before the mapping takes place. I attempted to use it as follows:

configure.CreateMap<IFrom, ITo>()
    .BeforeMap((x,y) => x.PrepareForMapping())
    .Include<FromImplementation1, ToImplementation1>()
    .Include<FromImplementation2, ToImplementation2>()
    ... ;

However the method is never being called, although the mapping itself is still working fine. I have placed breakpoints on every implementation of the PrepareForMapping() method and none of them are getting hit. So I came to the conclusion that I have either misunderstood how BeforeMap/AfterMap work, or I am doing something wrong (or both).

Many thanks.

For this one, you'll have to put the Before/After map on the derived types. This is because Include redirects the map to the polymorphic types. It's not an additive configuration, the Included maps replace the configuration.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM