Automapper: Using PreMap and AfterMap

I use automapper (successfully to the point) to execute a polymorphic map between two such interfaces:

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

It works great. In addition, however, interfaces include method signatures, the implementation of which is designed to modify objects before displaying:

 public interface IFrom { void PrepareForMapping(); } 

As you can see, the method has no return, but is intended to change the state of the object before performing the mapping. Currently, this method is called manually before the object is mapped, but my intention was to execute the method automatically before the mappings. I tried using it as follows:

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

However, this method is never called, although the display itself still works fine. I set breakpoints for each implementation of the PrepareForMapping () method, and none of them fall. Therefore, I came to the conclusion that I either misunderstood how PreMap / AfterMap works, or I'm doing something wrong (or both).

Many thanks.

+4
source share
1 answer

To do this, you will need to put the Before / After card on the derived types. This is due to the fact that Include redirects the map to polymorphic types. This is not an additive configuration; included cards replace the configuration.

+5
source

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


All Articles