Onion Architecture – Application and Domain Services Explained

javaobject-orientedonion-architecture

Onion architecture has a core which is composed by domain model, domain services and application services:

Onion architecture

I'm in doubt about those two service layers, domain services and application services.

I've been reading that they're related to DDD but I'm not familiar with DDD myself.

I'm not asking for the relationship, just an explanation of what those two layers do, and if possible a simple example in Java.

I've read that Domain Services are services used by the domain model and Application Services are services made accessible to the outer layers. Is this correct?

So a Repository would be a Domain Service and Application Services are related to the Use Cases of the application.

All of that is still unclear to me.

Best Answer

I've read that Domain Services are services used by the domain model ...

In DDD, domain services are part of the domain model/layer. They encapsulate business logic that doesn't neatly fit into a single entity in the model. A classic example is BankAccount (entity) and FundsTransferService (which operates on two accounts at a time).

... and Application Services are services made accessible to the outer layers.

Yes, this is correct. The application service orchestrates the execution of business logic for a use case. A typical application service might:

  1. Load related entities from a repository.
  2. Execute business logic using operations on entities or via domain services.
  3. Store the updated entities.

So a Repository would be a Domain Service ...

A repository is not a domain service, it simply provides a mechanism to store and query entities but does not house any business logic. The repository interface is still considered part of the domain layer though.

... and Application Services are related to the Use Cases of the application.

Yes, however, as mentioned above, they should only orchestrate use cases, not directly implement any business logic.