AutoMapper - why use Map over DynamicMap?

2019-02-16 08:48发布

问题:

Assuming the objects you're mapping with AutoMapper require no custom mappings, is there ever a point in doing this:

Mapper.CreateMap<Src, Dest>(); 
// ....
Mapper.Map(SrcObject, DestObj);

If no custom mappings are required, does the above approach gain you anything over just using DynamicMap without the need for any prior configuration?

Mapper.DynamicMap(SrcObject, DestObj);

I do understand that DynamicMap is required when you're mapping anonymous types, but I'm asking about whether DyanmicMap is ever not preferred for static types that require no custom mappings.

回答1:

Been a while since I last used Automapper, but if I remember correctly:

In order to use Map, you need to specify those Maps explicitly first via CreateMap. Afterwards you can validate your Configuration by calling AssertConfigurationIsValid.

This happens right after launching your application rather than encountering an error mid execution (given that you create the mappings and validate on startup, which is recommended).

Also some types do not match 1:1, so you would want to specify the exact mappings, not sure if DynamicMap makes use of the Maps you have introduced manually, actually I think it does not.
Just checked, DynamicMap falls back on existing Maps in the current version up on github.

It's also a matter of performance since DynamicMap uses reflection more heavily than the Map method, since you have already specified the mapping configuration and most of it does not have to bee asserted on the fly anymore. Not sure if the new version of Automapper is performing caching in this regard by now though.



标签: c# AutoMapper