DDD - which layer DTO should be implemented

user2105030 picture user2105030 · Jul 15, 2015 · Viewed 22.6k times · Source

I am learning about DDD so apologies if my question is naive. I think I need to use Local Data Transfer Object in order to display data to the users as a lot of properties are not part of any of Entity / Value Objects.

However, I am not sure where this DTO should be implemented - in a Domain Layer or in an Application Service Layer. The DTO implementation seems part of the Domain, but it means that when I create a collection of DTOs in the Service Layer and pass it to a Presentation Layer, I have to reference Domain Layer in Presentation Layer, which seems wrong.

What is the correct way to implement DTO using DDD principles?

Answer

Yorro picture Yorro · Jul 16, 2015

Define the DTO to the layer where the output should come from.

Relative to OP's question: place the DTO in the Domain Service Layer. DTO is an output of that layer, it make sense if you define it there. Don't put your DTO in the Domain Layer. The Domain Layer does not care about things outside of it's layer.

EDIT1 2018: (answer removed, see EDIT2)

EDIT2 2020: Again people seems to be confused with the terminologies. I will now use "Domain Service Layer" as my final answer, relative to OP's question and based on the following layer definitions.

  • Presentation Layer (closes to consumer)
    • IE: Api
    • Has Models or Dto definitions of its own with attributes relative to its layer. IE: If this is an Api then DTO has attributes like formatting or data type validations
    • This is the "Application Root" (means that it must reference both Domain Service layer, Data/Infrastructure Layer to be able to inject services)
    • Maps data from Domain.Service.Dto to Presentation.Dto
  • Domain Service Layer
    • Has Dto definitions of its own to be able to return data without exposing the domain entities.
    • Services
  • Domain Layer
    • Domain entities
    • May contain Interfaces bridging the infrastructure layer, defined in words that can be understood by the business, free from technical terms (IE: IExcelReport, IGoogleSheetReport, IRepository)
  • Data / Infrastructure Layer (closest to your storage of choice)
    • Database infrastructure (mapping).
    • Excel libraries if you define this layer as infrastructure code.

Some layers have "Application Service Layer" in them to keep the Domain Service Layer pure. You can extend as long as you define the layers properly