Introduction
In the previous lesson, we completed the repository implementations and the Unit of Work approach. We can now build application service classes that coordinate use cases instead of placing data-access code directly inside API endpoints. This layer does not deal with the user interface or the HTTP protocol. Its primary responsibility is to define the steps of a business workflow, use the required repository contracts, trigger domain rules, and return an appropriate DTO when the operation is complete.
In this lesson, we will use product management as an example. We will implement product listing, retrieving a single product, creating a product, and updating a product in an application service. The goal is not merely to write working CRUD code. We also want to limit service responsibilities, use repositories correctly, manage the entity lifecycle safely, and create a structure that can later support controllers, validation, logging, and authorization without mixing concerns.
The Role of an Application Service
An application service represents a use case in the application layer. Methods such as CreateProduct, UpdateProduct, and GetProducts represent application behaviors rather than low-level CRUD operations. The service should not know the database connection string, EF Core query details, or HTTP status codes.
A typical workflow can contain the following steps:
- Receive a request DTO or command.
- Check the required validations and preconditions.
- Create the relevant entity or load it through a repository.
- Change the entity by using domain behavior.
- Schedule an add or update operation through a repository.
- Commit the changes as a single operation through the Unit of Work.
- Map the entity to a response DTO.
The service orchestrates these steps, but it should not implement every detail itself. Rules such as requiring a product name or requiring a price greater than zero should be protected by the entity or the domain layer. A repository may be used to check uniqueness. Decisions such as returning HTTP 404 or HTTP 400 belong to the presentation layer.
Example Contracts and Models
Let us make the example concrete by using the contracts defined in the previous lesson. Assume that the following models are located in the Application project:
public sealed record CreateProductRequest(
string Name,
string Description,
decimal Price,
int CategoryId);
public sealed record UpdateProductRequest(
string Name,
string Description,
decimal Price,
int CategoryId);
public sealed record ProductResponse(
int Id,
string Name,
string Description,
decimal Price,
int CategoryId);The repository contract should express the behaviors required by the application layer. EF Core details from the Infrastructure layer remain behind this contract:
public interface IProductRepository
{
Task GetByIdAsync(int id, CancellationToken cancellationToken);
Task GetListAsync(CancellationToken cancellationToken);
Task ExistsByNameAsync(string name, int? exceptId, CancellationToken cancellationToken);
Task AddAsync(Product product, CancellationToken cancellationToken);
void Update(Product product);
}
public interface IUnitOfWork
{
Task SaveChangesAsync(CancellationToken cancellationToken);
} The exceptId parameter is especially important during updates. It prevents the service from treating the product’s existing name as a duplicate of itself. This detail shows why repository contracts should be designed around real application use cases rather than around generic persistence methods alone.
Implementing the Listing Workflow
A listing use case is usually one of the simplest application service operations. The service requests the data from the repository, maps the entity collection to response DTOs, and returns the result to the caller. Returning DTOs instead of entities is important because it prevents the persistence model from leaking into the API contract and protects clients from unnecessary entity changes.
public interface IProductService
{
Task GetListAsync(
CancellationToken cancellationToken);
Task GetByIdAsync(
int id,
CancellationToken cancellationToken);
Task CreateAsync(
CreateProductRequest request,
CancellationToken cancellationToken);
Task UpdateAsync(
int id,
UpdateProductRequest request,
CancellationToken cancellationToken);
} public sealed class ProductService : IProductService
{
private readonly IProductRepository _productRepository;
private readonly IUnitOfWork _unitOfWork;
public ProductService(
IProductRepository productRepository,
IUnitOfWork unitOfWork)
{
_productRepository = productRepository;
_unitOfWork = unitOfWork;
}
public async Task GetListAsync(
CancellationToken cancellationToken)
{
var products = await _productRepository
.GetListAsync(cancellationToken);
return products.Select(Map).ToList();
}
public async Task GetByIdAsync(
int id,
CancellationToken cancellationToken)
{
var product = await _productRepository
.GetByIdAsync(id, cancellationToken);
return product is null ? null : Map(product);
}
private static ProductResponse Map(Product product)
{
return new ProductResponse(
product.Id,
product.Name,
product.Description,
product.Price,
product.CategoryId);
}
} The Map method is intentionally private and stateless. If mapping becomes more complex, it can be moved to a separate mapper component. For a small use case, however, a readable private method avoids unnecessary abstraction.
Implementing the Entity Creation Workflow
When creating a product, the service should not save the request DTO directly as an entity. It should define the workflow explicitly and create the domain object through an appropriate constructor or factory method. This prevents the entity from being created in an invalid state.
public async Task CreateAsync(
CreateProductRequest request,
CancellationToken cancellationToken)
{
var nameExists = await _productRepository
.ExistsByNameAsync(request.Name, null, cancellationToken);
if (nameExists)
{
throw new BusinessRuleException("A product with the same name already exists.");
}
var product = Product.Create(
request.Name,
request.Description,
request.Price,
request.CategoryId);
await _productRepository.AddAsync(product, cancellationToken);
await _unitOfWork.SaveChangesAsync(cancellationToken);
return Map(product);
}The workflow first checks for a duplicate, then creates the entity, adds it through the repository, and commits it through the Unit of Work. The order matters. Adding an invalid entity to the repository before checking the business condition can make transaction boundaries and error handling unnecessarily difficult.
The entity’s Create method can protect domain rules:
public static Product Create(
string name,
string description,
decimal price,
int categoryId)
{
if (string.IsNullOrWhiteSpace(name))
{
throw new BusinessRuleException("Product name is required.");
}
if (price <= 0)
{
throw new BusinessRuleException("Product price must be greater than zero.");
}
return new Product(name.Trim(), description.Trim(), price, categoryId);
}Implementing the Entity Update Workflow
Updating an entity is different from creating one. The service first loads the existing entity. If it does not exist, the service can return null or throw an exception according to the application’s error policy. The controller can then translate that result into an HTTP 404 Not Found response.
public async Task UpdateAsync(
int id,
UpdateProductRequest request,
CancellationToken cancellationToken)
{
var product = await _productRepository
.GetByIdAsync(id, cancellationToken);
if (product is null)
{
return null;
}
var nameExists = await _productRepository
.ExistsByNameAsync(request.Name, id, cancellationToken);
if (nameExists)
{
throw new BusinessRuleException("A product with the same name already exists.");
}
product.Update(
request.Name,
request.Description,
request.Price,
request.CategoryId);
_productRepository.Update(product);
await _unitOfWork.SaveChangesAsync(cancellationToken);
return Map(product);
} When an EF Core-tracked entity is changed, calling Update may not be technically necessary in some repository implementations. However, if the repository contract explicitly exposes the operation, calling it makes the abstraction’s intent visible. The important point is consistency. If some services call Update and others do not, the codebase becomes difficult to understand.
Registering Services with Dependency Injection
Application services should not be created with the new keyword inside the presentation layer. Their dependencies should be supplied by the Dependency Injection container:
services.AddScoped<IProductService, ProductService>();Repository and Unit of Work registrations can be placed in an Infrastructure extension method. The API project can then depend on explicit entry points such as AddApplication and AddInfrastructure. Application services are commonly registered as Scoped because they are expected to share the same scope as the DbContext and Unit of Work during one HTTP request.
Service Responsibilities from a SOLID Perspective
An application service should not become a large class where every kind of code is collected. The following boundaries should be preserved:
- Single Responsibility: ProductService coordinates product use cases; it does not send emails, upload files, or generate reports.
- Dependency Inversion: The service depends on repository and Unit of Work contracts instead of a concrete DbContext.
- Open/Closed: Adding a new notification channel should not require changing the existing product CRUD workflow.
- Interface Segregation: Prefer focused contracts over a large repository interface containing dozens of unrelated methods.
If complex pricing, stock reservation, or campaign evaluation rules begin to appear inside the service, those behaviors can be moved to a domain service or to the relevant entity. The application service should continue to coordinate the workflow rather than becoming the owner of every business rule.
Common Mistakes
- Returning entities from the API: This can expose sensitive fields and tightly couple the API contract to the persistence model.
- Writing workflows inside controllers: The same use case becomes duplicated when it is called from another entry point, and testing becomes more difficult.
- Creating a new DbContext in every method: This breaks the intended Unit of Work scope and complicates transaction management.
- Implementing duplicate checks incorrectly during updates: The current record must be excluded from the uniqueness check. That is why
exceptIdis useful. - Forgetting
SaveChangesAsync: Adding an entity to a repository does not make the change permanent. The Unit of Work must commit it. - Mixing null and exception strategies: If one service returns null for a missing record while another throws an exception, client behavior becomes inconsistent. Establish a project-wide policy.
Short Practice Exercise
Complete the following exercise:
- Create
ICategoryServiceandCategoryService. - Add methods for listing categories and retrieving a category by id.
- Check for an existing category name when creating a category.
- Load the existing category during an update and exclude its id from the duplicate-name check.
- Return a
CategoryResponseinstead of returning the entity directly. - Register the service as
Scopedwith Dependency Injection.
Also pass a CancellationToken through repository calls and try writing unit tests with a mock repository. Test at least the missing-record, duplicate-name, and successful-update scenarios.
Conclusion
In this lesson, we transformed CRUD and listing operations into explicit workflows inside the application service layer. We saw that an application service is not merely a pass-through between a controller and a repository. It coordinates validation, entity creation, loading an existing record, invoking domain behavior, and committing changes through the Unit of Work.
A well-designed application service expresses the workflow clearly, does not duplicate domain rules, does not expose persistence details, and remains focused on one responsibility area. In the next steps, we will connect these services to API controllers, FluentValidation, centralized exception handling, and Swagger contracts.