Monday, December 17, 2018

Application Services Should Not Be Used in Read Operations Mosh Blog

Hi Mosh,
I agree with you that the repository must return only domain entities. If you want to return ViewModel objects, it’s possible to create a Service layer that would be responsible for get domain entities using a repository and convert to ViewModels. Finally, the controller(mvc or webApi) could use these services and know nothing about the entities.
Leave your comments.
Have a nice day!
Hi Clayton,
Services should not return ViewModels 
A ViewModel is part of the presentation layer which sits above the service layer. 
Mapping of domain objects to ViewModels is the responsibility of whoever wants to display those objects. 
In an ASP.NET MVC application, it’s the controller, in a WPF application it’s the Form (or Window).
Services are often misunderstood. Technically, your services should be used only for the write operations and not for reading data. 
It took me a little while to really grasp this. The reason is that if a controller needs some data from the database, it can simply use the repository interfaces to get the data. There is no need to go through a service layer for getting data. 
With Application Services in Read Operations, you’ll end up with services methods that have 1 line of code, which is simply delegating to the repository. What’s the point of these methods? Nothing but increasing the development and maintenance cost. I had a lot of services like these several years ago but eventually, I came to this realization that these methods are redundant and add absolutely no value.
Just to clarify, controller uses the repository interface (not the implementation). So it doesn’t go straight to the data access layer. Repository interfaces are part of the business layer or the core domain.
Hope that helps!


======================================================
My Take on above
Above Question is asking for decoupling the Presentation Layer or Controller from the 
Domain Layer. 
Typically Hexagonal Architecture asks for decoupling the UI/Presentation/Controller from the Domain Layer and it is done as follows in case of Fetch Operations
UI <== Controller <== AS <== Repository<==EF<==DB
ViewModel<==Model<==DomainObject
But Mosh is saying it wastage of time and code if we involve AS in the Fetch Operations
UI <== Controller <== Repository<==EF<==DB
ViewModel<==DomainObject

No comments:

Post a Comment