Search code examples
c#javadesign-patternsmulti-tierthree-tier

Pass DTO to service layer


Is it not bad practice to pass DTO object to service layer?

For now my service layer method look like this:

public save(MyEntity entity);

Mapping values from DTO to business entity (MyEntity) is done on presentation layer

But I want to change method signature to this:

public save(MyEntityDTO dto, String author);

And after it mapping from DTO to business entity will occur on service layer.

EDIT: I want it because I need opened hibernate session when mapping from DTO to business object, so all changes on entity will be automatically flushed.


Solution

  • Is it not bad practice to pass DTO object to service layer?

    Not only you could pass DTO objects to Service Layer, but you should pass DTO objects instead of Business Entities to Service Layer.

    Your service should receive DTOs, map them to business entities and send them to the repository. It should also retrieve business entities from the repository, map them to DTOs and return the DTOs as reponses. So your business entities never get out from the business layer, only the DTOs do.

    See the full answer to a similar question here.