Should services always return DTOs, or can they also return domain models?

it doesn’t feel right when domain model leaves business layer (service layer)

Makes you feel like you are pulling the guts out right? According to Martin Fowler: the Service Layer defines the application’s boundery, it encapsulates the domain. In other words it protects the domain.

Sometimes service needs to return data object that wasn’t defined in the domain

Can you provide an example of this data object?

If we should strictly stick to DTOs, should they be defined in service layer?

Yes, because the response is part of your service layer. If it is defined “somewhere else” then the service layer needs to reference that “somewhere else”, adding a new layer to your lasagna.

is it ok to return domain models all the way to controllers, or should we always use DTOs for communication with service layer?

A DTO is a response/request object, it makes sense if you use it for communication. If you use domain models in your presentation layer (MVC-Controllers/View, WebForms, ConsoleApp), then the presentation layer is tightly coupled to your domain, any changes in the domain requires you to change your controllers.

it seems it wouldn’t make much sense to create DTO that is the same as domain model)

This is one of the disadvantage of DTO to new eyes. Right now, you are thinking duplication of code, but as your project expands then it would make much more sense, specially in a team environment where different teams are assigned to different layers.

DTO might add additional complexity to your application, but so are your layers. DTO is an expensive feature of your system, they don’t come free.

Why use a DTO

This article provides both advantage and disadvantage of using a DTO, http://guntherpopp.blogspot.com/2010/09/to-dto-or-not-to-dto.html

Summary as follows:

When to Use

  • For large projects.
  • Project lifetime is 10 years and above.
  • Strategic, mission critical application.
  • Large teams (more than 5)
  • Developers are distributed geographically.
  • The domain and presentation are different.
  • Reduce overhead data exchanges (the original purpose of DTO)

When not to Use

  • Small to mid size project (5 members max)
  • Project lifetime is 2 years or so.
  • No separate team for GUI, backend, etc.

Arguments Against DTO

Arguments With DTO

  • Without DTO, the presentation and the domain is tightly coupled. (This is ok for small projects.)
  • Interface/API stability
  • May provide optimization for the presentation layer by returning a DTO containing only those attributes that are absolutely required. Using linq-projection, you don’t have to pull an entire entity.
  • To reduce development cost, use code-generating tools

Leave a Comment