Tyler Wright
Tyler Wright

Reputation: 825

Where should I convert my entities to DTO's?

My architecture looks like this:

I'm wanting to use AutoMapper to convert it. I would like my service layer to only know about DTOs, so I'm guessing I would have my Interfaces and my Repositories return the converted DTO. As for the other direction, I would assume that my Repositories will take DTOs and convert to Entities? Am I on the correct path here or am I in left field?

Upvotes: 2

Views: 3868

Answers (2)

David Masters
David Masters

Reputation: 8295

  1. Your repositories should only deal with domain aggregates, which are designed around behaviors and transactions.

  2. When processing commands, your application layer (web services) should invoke logic on the domain model, saving the aggregates back to the repositories.

  3. When the client needs data from the web service you have two options:

    • Fetch aggregates from repositories and map them to POCO DTO's (maybe using AutoMapper).
    • Create a thin data-access layer specifically for querying data direct to DTO's.

The latter approach is my preference. As I said, domain aggregates should be designed by behavior & transactions. They are not designed to show data on a screen. It's always an awkward process trying to map data from a properly designed domain entity (i.e. properly encapsulated) to a DTO for a consumer of the data (such as a UI). It's square peg in a round hole. It is much easier in my opinion to provide a thin data access layer that returns whatever data the client requires. The domain model need not be involved in this process; it's just data. This is the basic principle of CQRS.

In any case it should be the application layer (web services) converting the domain entities to DTO's.

Upvotes: 4

Leon Cullens
Leon Cullens

Reputation: 12496

Your service layer should return entities, and your presentation layer (where Controllers reside imho) should translate the entities to objects that map to your user interface (the DTOs). This, of course, also implies that your repositories will return normal entities.

Don't forget to create the mappings only once. Create a bootstrapper or something that creates all the mappings, then you only have to call Mapper.Map() in your controller.

Upvotes: 1

Related Questions