Search code examples
c#domain-driven-design

Instead of use AutoMapper, map entities in constructor


Since I dont want to use AutoMapper, I desided to map entities in their constructor. For example: I map entity from database to domain entity in domain enitie's constructor, and map domain entity to view entity in view entity constructor. But I dont fell so sure about that approach, I'm not so good in DDD but seems like this approach disrupts DDD. So I want to get know if this approach fit DDD, and maybe there's more better approaches. Database entity to domain Product domain entity to view entity


Solution

  • There are a few issues with your approach.

    1. Separation of Concerns: now your database knows that you are using a database, and it even knows the shape of the datatable. What happens if you want to switch from an Sql Database to a NoSql database? You would have to modify the constructor or create a new one and then make sure that all consumers are modified accordingly.
    2. The ubiquitous language is broken. So, a third party (Stakeholder for example) couldn't look at your code and understand it without some developer experience. What your ubiquitous language is saying in essence is "My product requires a Database object". That's probably not true; what you are usually trying to say is "My product can be serialized". How you serialize it is not a concern of the Product.
    3. You have also inadvertently told anyone reading your code that there's no such thing as a "New Product" because there's no way to represent a New Product(a Product prior to being saved) in your code.

    What you should be doing instead is leaving the job of Serializing and Hydrating an object to a "Repository" and leave the job of creating a new object to a "Factory". Automapper helps you implement a repository with ease. Without Automapper, you would have to write and figure out if an object is "dirty" or new and whether to do an insert or update and translate all of that into Repository commands. Not impossible but super daunting!

    https://learn.microsoft.com/en-us/dotnet/architecture/microservices/microservice-ddd-cqrs-patterns/infrastructure-persistence-layer-design

    https://culttt.com/2014/12/24/factories-domain-driven-design

    This is of course a simplified answer as the answer to your question could go several layers deeper. Please let me know if there's a detail you would want me to delve into a little bit more.