Sunday, August 21, 2022

Domain Service

Domain service is used to encapsulate business logic, which could not sit comfortably within an entity or aggregate in the system. Usually, a domain service is created then multiple entities are involved and behavior can't be owned by a single entity.

Characteristics


Every domain service has to match such characteristics:
  • Represent behavior
  • Stateless
  • No identity

public class PricingService : DomainService, IPricingService
{
    public Money CalculateTotalPriceFor(IList<item> items, Coupon coupon) 
    {
        // ...
    }
}


Application Service


Application services are used to implement the use cases of an application. They do not contain business logic. They are responsible for orchestration, for hydrating domain objects from a database and mapping.

The main difference between application service and domain services is that domain service holds domain logic where application services don’t.

public interface ProfileService : ApplicationService, IProfileService
{
    public Task<Profile> CreateProfileAsync(string username)
    {
        // ...
    }

    public Task<Profile?> GetProfileAsync(int id, CancellationToken cancellationToken)
    {
        // ...
    }
}

Application services are similar to ASP.NET  Core controller actions. Controller actions contain logic to control the user interface interactions in the same manner that application services contain logic that represents business tasks or use cases that coordinate communication with services and objects within the domain layer.

In case then ASP.NET  Core controllers are used, there is no need to created dedicated application controllers. Controllers can be used as application services to implement use cases of an application.

As an alternative, commands can be used to process business use cases.


Infrastructure Service


Infrastructure Services is used to abstract technical concerns. The are responsible notifying other systems of changes in domain state via messaging systems or web calls, authorization, and logging.

public class MailService : InfrastructureService, IMailService
{
    public virtual async Task SendMailAsync(MailMessage mailMessage)
    {
        // ...
    }
}

No comments:

Post a Comment