Skip to content

AppServices

An Application Service is a service that contains application/use-case logic. Application Services implement the IAppService marker interface, and are automatically exposed by the MVC Module as API Controllers, by following a set of Routing Conventions

Implementation Example

AppServices are defined in the Application Layer. If you have an Application.Contracts project, you would define an interface for your AppService there:

C#
1
2
3
4
5
6
public interface IServiceOrderAppService : IAppService
{
    Task<ServiceOrderDTO> CreateAsync(
        CreateServiceOrderDTO creationInfo,
        CancellationToken cancellationToken = default);
}

The implementation for your service should live in the Application Layer:

C#
public class ServiceOrderAppService : IServiceOrderAppService
{
    private readonly IRepository<Guid, ServiceOrder> serviceOrderRepository;
    private readonly IMapper mapper;

    public void ServiceOrderAppService(
        IRepository<Guid, ServiceOrder> serviceOrderRepository,
        IMapper mapper)
    {
        this.serviceOrderRepository = serviceOrderRepository;
        this.mapper = mapper;
    }

    public async Task<ServiceOrderDTO> CreateAsync(
        CreateUpdateServiceOrderDTO creationInfo,
        CancellationToken cancellationToken)
    {
        var serviceOrder = new ServiceOrder();

        serviceOrder.ChangeDescription(creationInfo.Description);
        serviceOrder.AdvanceState(ServiceOrderState.New);

        await repository.CreateAsync(serviceOrder, cancellationToken)
            .ConfigureAwait(false);

        return this.mapper.Map<ServiceOrderDTO>(serviceOrder);
    }
}
  1. Use async methods 'all the way' when possible.
  2. Always receive a CancellationToken and pass it down the calling chain.
  3. Always inject interfaces, it will allow for easier testing.
  4. AppServices never contain domain business logic; they coordinate domain entities instead.
  5. AppServices receive and return DTOs.

Naming convention

Always use the AppService suffix when naming application service classes. The Suite will automatically remove it leaving your classes named properly, and your API endpoints as well.

Auto registration

IAppService implementations will be auto-registered in DI by the Suite Framework, you don't need to take care of registering it as dependency.

Excluding AppServices

There may be times when you need to exclude an AppService from being registered as an API Controller.

It might be useful to exclude AppServices that are for development/diagnostics from production builds, or perhaps even better you can enable/disable them from IConfiguration

To exclude an AppService, we use the EndpointsModule options, like below:

C#
1
2
3
4
builder.DependsOn<EndpointsModule, EndpointsModuleOptions>(ops =>
{
    ops.DynamicApiControllerOptions.ExcludeAppService<MyExcludedAppService>();
});