Contents
Should services always return DTOs or can they also return domain models?
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.
Should DTOs be used?
Coupling. The reason you want to use DTOs is that you want clients to couple to that contract, not to your internal data structures. This allows you to modify and evolve your internals freely without breaking clients.
What is the point of a DTO?
DTOs are called Data Transfer Objects because their whole purpose is to shift data in expensive remote calls. They are part of implementing a coarse grained interface which a remote interface needs for performance.
How do you convert DTO to entity?
Using Model Mapper Library Thus, we can use model mapper to convert entity to dto or dto to entities. First, we need to add model mapper dependency. Next, we can create a @Bean factory method to create ModelMapper instance. This way, the model mapper instance will be available for injection on the application level.
Why do we convert DTO to entity?
DTO give us benefit to hide our entity from client that using API and help us to maintain our code if we want to change our internal database structure. Additionally, if you work with a lot of development team, you can use DTO as a library. DTO class and Entity class have different responsibility.
How does the service layer return DTOs to controller?
Instead, the service layer should encapsulate your domain model and return DTOs via its interface. The mapping should happen inside that layer itself. So coming back to the problem which the OP’s having, he’s trying to communicate with another service to get some data filled into his domain object.
When to convert model to DTO in controller?
Convert the model to a DTO in the controller (i.e. in your web application) just prior to serialization. This allows you to use your services as you desire, and save the DTOs for when they are actually required. IMO the accepted answer promotes something which you should not be doing in the service layer, ie returning your domain objects.
When do we need to return DTOs to a service?
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).
How are DTOs used in a MVC service?
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). I’v read countless articles about using, not using, mapping and passing DTOs.