Programing

서비스가 항상 DTO를 반환해야합니까, 아니면 도메인 모델을 반환 할 수 있습니까?

lottogame 2020. 6. 30. 08:24
반응형

서비스가 항상 DTO를 반환해야합니까, 아니면 도메인 모델을 반환 할 수 있습니까?


대규모 응용 프로그램을 설계하고 있으며 DDD 기반의 다중 계층 아키텍처를 사용합니다.

데이터 계층 (리포지토리 구현), 도메인 계층 (도메인 모델 및 인터페이스 정의-리포지토리, 서비스, 작업 단위), 서비스 계층 (서비스 구현)을 갖춘 MVC가 있습니다. 지금까지 모든 계층에 걸쳐 도메인 모델 (주로 엔터티)을 사용하고 DTO를 뷰 모델로만 사용합니다 (컨트롤러에서 서비스는 도메인 모델을 반환하고 컨트롤러는 뷰 모델을 뷰에 전달합니다).

DTO 사용, 사용 안 함, 매핑 및 전달에 대한 수많은 기사를 읽었습니다. 명확한 답변이 없다는 것을 이해하지만 도메인 모델을 서비스에서 컨트롤러로 되돌릴 수 있는지 확실하지 않습니다. 컨트롤러가 항상 뷰 특정 뷰 모델을 생성하기 때문에 도메인 모델을 반환해도 여전히 뷰로 전달되지 않습니다.이 경우 합법적 인 것처럼 보입니다. 반면, 도메인 모델이 비즈니스 계층 (서비스 계층)을 떠날 때 기분이 좋지 않습니다. 때로는 서비스가 도메인에 정의되지 않은 데이터 객체를 반환해야하는 경우 매핑되지 않은 도메인에 새 객체를 추가하거나 POCO 객체를 생성해야합니다 (일부 서비스는 도메인 모델을 반환하기 때문에 추악합니다) 효과적으로 DTO를 반환).

문제는-뷰 모델을 엄격하게 사용하는 경우 도메인 모델을 컨트롤러로 되돌려 보내는 것이 좋습니까, 아니면 서비스 계층과의 통신에 항상 DTO를 사용해야합니까? 그렇다면 어떤 서비스가 필요한지에 따라 도메인 모델을 조정해도 괜찮습니까? (서비스가 도메인을 가지고 있어야하기 때문에 솔직히 그렇게 생각하지 않습니다.) DTO를 엄격하게 고수해야한다면 서비스 계층에서 정의해야합니까? (그렇다고 생각합니다.) 때로는 DTO를 사용해야한다는 것이 분명합니다 (예 : 서비스가 많은 비즈니스 로직을 수행하고 새로운 객체를 생성하는 경우). 때로는 도메인 모델 만 사용해야한다는 것이 분명합니다 (예 : 멤버십 서비스가 빈약 한 사용자 ( s)-도메인 모델과 동일한 DTO를 만드는 것이별로 의미가없는 것 같습니다.)-일관성과 우수 사례를 선호합니다.

기사 도메인 vs DTO vs ViewModel-어떻게 그리고 언제 사용합니까? (및 일부 다른 기사)는 내 문제와 매우 유사하지만이 질문에 대답하지 않습니다. 기사 EF를 사용하여 저장소 패턴으로 DTO를 구현해야합니까? 또한 비슷하지만 DDD를 다루지 않습니다.

면책 조항 : 디자인 패턴이 존재하고 멋지 기 때문에 디자인 패턴 만 사용하려고하지는 않지만, 좋은 디자인 패턴과 관행을 사용하고 싶습니다. 응용 프로그램 전체를 디자인하고 분리하는 데 도움이되기 때문입니다. 우려 할 점은 적어도 현재로서는 특정 패턴을 사용하는 것만으로는 "필요하지 않다"는 것입니다.

언제나 그렇듯이 감사합니다.


도메인 모델이 비즈니스 계층 (서비스 계층)을 떠날 때 기분이 좋지 않습니다.

내장을 바로 잡아 당기는 느낌이 들까 요? Martin Fowler에 따르면 : 서비스 계층은 응용 프로그램의 경계를 정의하고 도메인을 캡슐화합니다. 다시 말해 도메인을 보호합니다.

때때로 서비스는 도메인에 정의되지 않은 데이터 객체를 반환해야합니다

이 데이터 개체의 예를 제공 할 수 있습니까?

DTO를 엄격하게 준수해야하는 경우 서비스 계층에서 정의해야합니까?

예, 응답은 서비스 계층의 일부이기 때문입니다. "다른 곳"으로 정의 된 경우 서비스 계층은 "다른 곳"을 참조하여 라자냐에 새 계층을 추가해야합니다.

도메인 모델을 컨트롤러로 되돌려 보내는 것이 좋습니까, 아니면 서비스 계층과의 통신에 항상 DTO를 사용해야합니까?

DTO는 응답 / 요청 객체이며, 통신에 사용하는 것이 좋습니다. 프리젠 테이션 레이어 (MVC- 컨트롤러 / 뷰, WebForms, ConsoleApp)에서 도메인 모델을 사용하는 경우 프리젠 테이션 레이어가 도메인과 밀접하게 연결되어 있으며 도메인을 변경하면 컨트롤러를 변경해야합니다.

도메인 모델과 동일한 DTO를 만드는 것은 의미가없는 것 같습니다.)

이것은 새로운 시각에 대한 DTO의 단점 중 하나입니다. 지금 은 코드 중복을 생각하고 있지만 프로젝트가 확장되면 특히 다른 팀이 다른 레이어에 지정된 팀 환경에서 훨씬 더 의미가 있습니다.

DTO는 애플리케이션에 추가적인 복잡성을 추가 할 수 있지만 계층도 복잡합니다. DTO는 시스템의 비싼 기능이며 무료로 제공되지 않습니다.

DTO를 사용해야하는 이유

이 기사에서는 DTO 사용의 장단점을 모두 제공합니다. http://guntherpopp.blogspot.com/2010/09/to-dto-or-not-to-dto.html

다음과 같은 요약 :

사용시기

  • 대규모 프로젝트의 경우.
  • 프로젝트 수명은 10 년 이상입니다.
  • 전략적이고 미션 크리티컬 한 애플리케이션.
  • 대규모 팀 (5 명 이상)
  • 개발자는 지리적으로 분산되어 있습니다.
  • 도메인과 프리젠 테이션이 다릅니다.
  • 오버 헤드 데이터 교환 감소 (DTO의 원래 목적)

사용하지 않을 때

  • 중소 규모 프로젝트 (최대 5 명)
  • 프로젝트 수명은 2 년 정도입니다.
  • GUI, 백엔드 등을위한 별도의 팀이 없습니다.

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

In my experience you should do what's practical. "The best design is the simplest design that works" - Einstein. With that is mind...

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

Absolutely it's ok! If you have Domain Entities, DTO's and View Models then including database tables you have all the fields in the application repeated in 4 places. I've worked on large projects where Domain Entities and View Models worked just fine. The only expception to this is if the application is distributed and the service layer resides on another server in which case DTOs are required to send across the wire for serialization reasons.

If so, is it ok to adjust domain models based on what services need? (Frankly I don't think so, since services should consume what domain has.)

Generally I'd agree and say no because the Domain model is typically a reflection of the business logic and doesn't usually get shaped by the consumer of that logic.

If we should strictly stick to DTOs, should they be defined in service layer? (I think so.)

If you decide to use them I'd agree and say yes the Service layer is the perfect place as it's returning the DTOs at the end of the day.

Good luck!


It seems that your application is big and complex enough as you have decided to go through DDD approach. Don't return your poco entities or so called domain entities and value objects in you service layer. If you want to do this then delete your service layer because you don't need it anymore! View Model or Data transfer objects should live in Service layer because they should map to domain model members and vice versa. So why do you need to have DTO? In complex application with lots of scenarios you should separate the concerns of domain and you presentation views, a domain model could be divided into several DTO and also several Domain models could be collapsed into a DTO. So it's better to create your DTO in layered architecture even it would be the same as your model.

Should we always use DTOs for communication with service layer? Yes, you have to return DTO by your service layer as you have talk to your repository in service layer with domain model members and map them to DTO and return to the MVC controller and vice versa.

Is it ok to adjust domain models based on what services need? A service just talks to repository and domain methods and domain services, you should solve the business in your domain based on your needs and it's not the service task to tell the domain what is needed.

If we should strictly stick to DTOs, should they be defined in service layer? Yes try to have DTO or ViewModel just in service later because they should be mapped to domain members in service layer and it's not a good idea to places DTO in controllers of your application(try to use Request Response pattern in your Service layer), cheers!


So far, we use domain models (mostly entities) across all layers, and we use DTOs only as view models (in controller, service returns domain model(s) and controller creates view model, which is passed to the view).

Since Domain Model provides terminology (Ubiquitous Language) for whole your application it is better to use Domain Model widely.

The only reason to use ViewModels/DTOs is an implementation of MVC pattern in your application to separate View (any kind of presentation layer) and Model (Domain Model). In this case your presentation and domain model are loosely coupled.

Sometimes service needs to return data object that wasn't defined in the domain and then we either have to add new object to the domain that isn't mapped, or create POCO object (this is ugly, since some services return domain models, some effectively return DTOs).

I assume that you talk about Application/Business/Domain Logic services.

I suggest you return domain entities when you can. If it is needed to return additional information it is acceptable to return DTO that holds several domain entities.

Sometimes, people who use 3rd part frameworks, that generates proxies over domain entities, face difficulties exposing domain entities from their services but it is only a matter of wrong usage.

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

I would say it is enough to return domain entities in 99,9% cases.

In order to simplify creation of DTOs and mapping your domain entities into them you can use AutoMapper.


I'm late to this party, but this is such a common, and important, question that I felt compelled to respond.

By "services" do you mean the "Application Layer" described by Evan's in the blue book? I'll assume you do, in which case the answer is that they should not return DTOs. I suggest reading chapter 4 in the blue book, titled "Isolating the Domain".

In that chapter, Evans says the following about the layers:

Partition a complex program into layers. Develop a design within each layer that is cohesive and that depends only on the layers below.

There is good reason for this. If you use the concept of partial order as a measure of software complexity then having a layer depend on a layer above it increases complexity, which decreases maintainability.

Applying this to your question, DTOs are really an adapter that is a concern of the User Interface / Presentation layer. Remember that remote/cross-process communication is exactly the purpose of a DTO (it's worth noting that in that post Fowler also argues against DTOs being part of a service layer, although he isn't necessarily talking DDD language).

If your application layer depends on those DTOs, it is depending on a layer above itself and your complexity increases. I can guarantee that this will increase the difficulty of maintaining your software.

For example, what if your system interfaces with several other systems or client types, each requiring their own DTO? How do you know which DTO a method of your application service should return? How would you even solve that problem if your language of choice doesn't allow overloading a method (service method, in this case) based on return type? And even if you figure out a way, why violate your Application Layer to support a Presentation layer concern?

In practical terms, this is a step down a road that will end in a spaghetti architecture. I've seen this kind of devolution and its results in my own experience.

Where I currently work, services in our Application Layer return domain objects. We don't consider this a problem since the Interface (i.e. UI/Presentation) layer is depending on the Domain layer, which is below it. Also, this dependency is minimized to a "reference only" type of dependency because:

a) the Interface Layer is only able to access these Domain objects as read-only return values obtained by calls to the Application layer

b) methods on services in the Application Layer accept as input only "raw" input (data values) or object parameters (to reduce parameter count where necessary) defined in that layer. Specifically, application services never accept Domain objects as input.

The Interface Layer uses mapping techniques defined within the Interface Layer itself to map from Domain objects to DTOs. Again, this keeps DTOs focused on being adapters that are controlled by the Interface Layer.


I'd suggest analyzing these two questions:

  1. Are your upper layers (i.e. view & view models / controllers) consuming the data in a different way of what the domain layer exposes? If there is a lot of mapping being done or even logic involved I'll suggest revisiting your design: it should probably be closer to how the data is actually used.

  2. How likely is it that you deeply change your upper layers? (e.g. swapping ASP.NET for WPF). If this is highly unlike and your architecture is not very complex, you may be better off exposing as many domain entities as you can.

I'm afraid it is quite a broad topic and it really gets down to how complex your system is and its requirements.


In my experience, unless you are using an OO UI pattern (like naked objects), exposing the domain objects to the UI is a bad idea. This because as the application grows, the needs from the UI change and force your objects to accommodate those changes. You end up serving 2 masters: UI and DOMAIN which is a very painful experience. Believe me, you don't want to be there. The UI model has the function of communicating with the user, the DOMAIN model to hold the business rules and the persistence models deals with storing data effectively. They all address different needs of the application. I'm in the middle of writing a blog post about this, will add it when it's done.

참고URL : https://stackoverflow.com/questions/21554977/should-services-always-return-dtos-or-can-they-also-return-domain-models

반응형