Which layer should be used for conversion to DTO from Domain Object - layer

We are creating rest api's with Spring Boot. We have three layers in our project(Repository, Service and Controller).
Lets say I have GetUser api in my controller that return UserDTO object.
#GetMapping
public UserDTO getUser() {
return userService.getUser();
}
Whether userService.getUser() returns UserDTO object or it returns User object and it is converted to UserDTO object in the controller? Which one is better way?
Shortly, domain object to DTO object conversion, should be done in service layer or controller layer?

I think there is no "better way" for converting your domain objects to your DTO objects, it's a matter of taste. In my projects I convert the domain objects to the DTO in the service layer as part of my "business logic". So you reduce the accessability of your domain objects only to your service layer. Furthermore I want to reduce the "logic" inside my controllers as they are part of the application layer.
PS: If you are looking for several ways to convert your domain objects to your DTOs have look at one of my latest Stackoverflow questions (How to properly convert domain entities to DTOs while considering scalability & testability)

It depends on application needs and architecture. Idea is to keep dto conversion at edge. It is generally prefer to have dto and domain conversion at the controller level. If you want to keep services/business logic independent of consumer, then it is always better to have at api level. This becomes more clear if your service has been consumed by more than one consumer.

In my experience, the conversion should be on the Controller layer. This gives an advantage that able to reuse other service methods with the return object is the origin.
This point may be important sometimes because the DTO object often reduce fields from the origin object. Therefore, we need more code to get these reduced fields, making our code ugly and duplicated.
I know that it would be moving logic to the controller layer, but it is a tradeoff.

Here is what I do in general:
My service layer takes dto as an argument.
I do the conversion at the service layer, because I might need to apply some business logic when converting.
But my service layer always returns entity. And I do the conversion at the controller level. This makes my service is clean and independent of the consumer. It may happen that my service might be consumed by another service and need entity not the dto.
In summary:
Dto —> Entity (Service layer)
Entity —> Dto (Controller layer)

Related

How to deal with complex queries in MVC?

Let's say you have three models, Organization, OrganizationUser, and User.
You need to handle the following reqs:
When a user creates an organization, they should become a user associated with that organization (a row in OrganizationUser table).
If any of the operations above fail, the entire "flow" should fail. This should be implemented with a transaction.
Here are the three best ways I think you can architect it:
In the controller, create TXN, pass it to the Organization and OrganizationUser models to create their respective rows. Rollback if needed. Controller contains the business logic (has user paid, what type of org... etc).
In the controller, call CreateOrganizationService which handles the transaction creation, abstracting it away from the controller; passes it into the models. CreateOrganizationService is where we'll keep most of the business logic
Have Organization model require OrganizationUser model and take care of the transaction creation, the business logic, and creation of the OrganizationUser row.
Is there a better way of thinking about this, or different approaches/patterns I can apply?
The Controller's job is to translate incoming requests into outgoing responses. In order to do this, the controller must take request data and pass it into the Service layer. The service layer then returns data that the Controller injects into a View for rendering.
The model in MVC is not a class, it's a layer.
The Model's job is to represent the problem domain, maintain state, and provide methods for accessing and mutating the state of the application. The Model layer is typically broken down into several different layers:
Service layer - this layer provides cohesive, high-level logic for related parts of an application. This layer is invoked directly by the Controller and View helpers.
Data Access layer - (e.g. Data Mapper) this layer provides access to the persistence layer. This layer is only ever invoked by Service objects.
Value Objects / Entity layer - this layer provides simple, data-oriented representations of "leaf" nodes in your model hierarchy.
To your question: Don't put business logic or transactions into the controller. Put the business logic (and transactions) stuff into the Service class (part of the model layer).
Source
You can implement a service layer in between controller and repository where you can handle the business logic and making the controller clean. And all the operations related to database (CRUD) can be done in repository.
Refer this :
Difference between Repository and Service Layer?
from your controller, you can call:
svc.CreateOrganization(<params>);
I probably wouldnt pass the model into the service. I would pass the actual data parameterized out for each piece of data b/c inside of your CreateOrganization call you should be calling into the data access layer which should use DAOs to store data.

DTO and Domain Object, WCF as well as DB Layer interaction

I have asp.net mvc 2 application. i have confusion creating DTO and domain entities.
MVC Controller Integration points:
1) third party WCF
2) DB Layer
WCF is returning Persons information of a particular company and some information about company.
I have generated proxy of WCF and written a service wrapper on the proxy.
Service wrapper is talking to WCF and Mapping the results to DTO clas ContactsDTO
Service layer is in different project.
Following are my domain classes
Company
Person
DTO class
//it contains
class ContactsDTO
{
Person person, Company[] company
}
Controller action calls the wrapper with companyID and get the object of DTO class.
and update the company information from dto. it updates the company information in Session and pass the Company[]array to some other operations.
DB interaction:
Now depending upon some business logic, i have to insert Person-ids and company id along with some other information in Database.
for this i have created another
class DBDTO
{
Person person, Company[] company, OtherInfo otherInfo[]
}
this DBDTO is prepared and passed to DB Layer(which is using Linq to sql).
Questions
Is it write way to do. Any improvement in DTO interaction? What all
changes i can do to improve the overall architecture
Another alternative to DB-bound objects being translated to DTOs (which takes time) is to use POCO (Plain Old CLR Objects) and use them directly as your Domain Model, objects that can be stored in the DB and objects that are communicated to Controllers for visualization.
This can get you started: Working with POCO Entities
This approach has several advantages
Your POCO entities are independent of the underlying DB implementation
Your POCO entities can be unit-tested without presence of a Database
You can easily serialize them into a service response (if you are building an API) using DataContractSerializer or DataContractJsonSerializer
I agree with Algirdas to differentiate models because of different responsibilities.
By the way: MVC is not a layer concept. It's a concept of three responsibilities and their collaboration. Although it is often (mis)used for layering you will encounter problems with SRP if you only separate your application layers applying "MVC". If you have MVC per layer then you go well.
After all if it is a small application you maybe never reach the critical mass to have problems with the architecture.

Where to place DTO <==> Entity translator in WCF service?

I have the following design :
My Design
My Design http://s15.postimg.org/3zha8rzqh/Design_Idea.png
I will have a class called 'ProductDTO' in my service layer (the left service).
When the 'Update Product ( ProductDTO )' operation contract is called - it should call the 'Update Product' function in the Business Logic Layer.
In the database (the 'Data Access Layer') there is an entity called 'Product', and because I use LINQ-To-Entities I will also have a class there called 'Product'.
My question is - where do I translate from 'ProductDTO' to 'Product' ?
Should I have a 'Translate_ProductDTO_To_Product' function in the service layer ?
It seems the most logic answer, because that is the only layer that knows what 'ProductDTO' is.
But this means that the service layer will also have to know what 'Product' is, and thus will have to reference the data access layer assemblies.
Is this correct ?
I thought that the service layer should only reference the business logic layer, and that the business logic layer should only reference the data access layer, and that the service layer should know nothing about the DAL.
It seems your confusion may stem from assuming the Product class in your data layer is actually the Product entity. Generally in domain driver design, your business entities live-in/are the business logic layer. Usually these class are "ignorant" of persistence which is the responsibility of the data access layer (typically using an object-relational mapper framework).
In practice, your service will require references to both to the domain model (business layer) and the data access layer to perform useful work. Both the WCF service code and the data access layer should depend on the domain model but the domain model should not have dependencies on either the data access layer or the WCF service code.
Map the DTO to your domain entities in your service layer. Your service layer needs to know about DTOs and the entities it is mapping to (and from). I strongly advise you use a tool like AutoMapper to do the mapping rather than hand-crafting.
Your service layer should not reference your DA layer (or assembly). Your BL later will need to reference your DA layer to persist the entities.
Edit:
Your business entites probably should not be under a DA namespace. If you are using an ORM tool to generate them, make sure you put any DDD logic in the other half of a partial class.

WCF Data Contracts DTO

In my application I am making a service call and getting back populated WCF Data Contract object. I have to display this data in a grid. Is it good practice to bind the data contract to the grid ?
Josh
Is it good practice to bind the data contract to the grid ?
Yes. There is nothing wrong with what you are doing.
Let me elaborate: what you have received back from the WCF service is a standard object (sometimes referred to as a DTO - Data Transfer Object). You have not received a DataContract - you have received an object that used a DataContract to control the serialization process between the WCF service and your client. The DataContract can control or dictate what you get, but once you have that object you are free to treat it as you wish.
Assuming that all of your DTOs are friendly for data binding then shouldn't have a problem binding your WCF DTOs to a grid.
Some scenarios where you might not want to bind directly to your DTOs are:
Your DTOs are not easy to bind with their current definition (e.g. nested objects/properties)
You need to support notification of changes to the binding client (typically done using INotifyPropertyChanged)
You wish to insulate your UI code from changes to the WCF DTOs. This could be because you don't control the DTO definition or you expect frequent changes to the DTO definitions and you don't want to frequently change your UI code. Of course, if the DTO does change then you will have to modify code but you could isolate those changes to a small translation layer.
I'd recommend the use of view models for any data binding or data display (MVVM) on server side (i.e. MVC) and client side (javascrip) rendering.
The main risk of using DTOs returned by domain is that if DTOs are refactored for any reason (i.e. properties are renamed, extracted into other objects or more objects are merged into one) the UI will break and will require update.
DTOs are the contract for what is returned by your domain, whereas the view models are the contract for what the UI requires. The two are controlled by different requirements and although those requirements can be applied to the same set of objects the result is usually a mixture what is just wrong, not to mention that requirements what apply only to UI or domain will trigger changes in the other party.
I.e. views often require data from more DTOs, or different views require a different subset of data from the same DTO and in both cases the DTO should not change only to accomodate what a concrete view requires.
It is also easier to identify what the requirements for a view are if the views have a view model, rather than having the same DTO passed in to more views.

Returning NHibernate mapping classes from WCF services

I have a server that handles the database access and a client that consumes the information. The communication from the client to the server is through a WCF service.
When the NHibernate POCO is returned from the service are all the objects in the object graph serialized? If so, is there a way to change it?
I'm also thinking of not returning the NHibernate POCO and instead return an object with only the essential information.
What do you do in these cases?
Use data-transfer objects to move the data from the server to the client. Your business (domain model) objects should not necessarily be exposed outside the core of the application, but should be considered a protected asset.
You can use AutoMapper to automate the translation from business objects to data-transfer objects.
Yeah, you probably want a DTO for this. It's usually considered better to not pass your data objects to the outside world, but also passing hibernate objects directly out of a service can give you some weird behavior, especially if you have lazily loaded collections.