C# – Using Automapper to Map DTOs to Domain Objects

cdomain-driven-design

Please see the article here: http://enterprisecraftsmanship.com/2017/02/16/on-automappers/

The writer advises against using Automapper to map DTOs to domain objects as it can cause problems with validation. Why is this? My domain models have a function called Validate(), which is called by the Service Layer i.e. it has to be called explicitly by the service layer (and by the domain layer to make sure that the service layer has done its job. It is similar to how the same writer recommends validation in this article: http://enterprisecraftsmanship.com/2016/09/13/validation-and-ddd/ (see IsValid() method).

How does Automapper bypass validation if it is used to map DTOs to Domain Objects?

Best Answer

From what I gather, his point is that domain objects will not generally map 1-to-1 to the DTOs, in the sense that they will not have all the same properties. In fact, domain objects may have very few getters and setters; they may even have none at all. This is related to the the "tell, don't ask" principle: if responsibilities are properly distributed across classes, domain objects will have very little need to pull data from each other in order to achieve something. Instead, they will mostly call methods on each other. Now, while you can use Automapper-like libraries to copy data from DTOs to the domain objects in such a scenario, the author's point is that this requires a fairly complicated setup, which defeats the purpose of having an automapper.

They can perform the mapping of course, but that would require setting up quite sophisticated mapping rules which diminishes the value of having the automapper in the first place.

If the design of your domain objects is influenced by the desire to support easy automapping, then you'll break encapsulation by introducing getters and setters that are not really needed. This could introduce problems with validation. E.g., without automapping considerations, your domain objects may be designed in such a way so that it is not possible to invoke a method or a property and have the object end up in an invalid state when the control returns to the caller. If you introduce getters and setters and a Validate() method, then it becomes possible for an object to be in an invalid state between the a call to a setter, and a call to Validate(). That may or may not be OK - as everything else, it's a trade-off.