Introduction
In the previous lesson, we structured the Data Access layer with Repository and Unit of Work patterns. That structure organizes database access, but an application’s behavior is not defined only by inserting, deleting, or listing data. Rules such as preventing orders for inactive products, rejecting sales when stock is insufficient, or preventing duplicate active products are business rules.
In this lesson, we will centralize those rules in services inside the Business layer instead of scattering them across controllers and repositories. A service evaluates an incoming request, performs the required validation, coordinates Data Access components, and returns a meaningful result to the API layer.
Our examples use a product and order scenario. The code assumes that the previous lesson introduced contracts such as IProductRepository, IOrderRepository, and IUnitOfWork.
Responsibilities of the Business layer
The Business layer is the decision-making boundary between the API and Data Access layers. The API layer handles HTTP requests and responses, while the Data Access layer handles persistence details. The Business layer coordinates use cases and prevents the API and Data Access layers from becoming tightly coupled.
Distribution of responsibilities
| Layer | Main responsibility | Example |
|---|---|---|
| API | HTTP communication, routes, status codes, and DTO input | POST /api/orders |
| Business | Business rules, validation, decisions, and workflow coordination | Is stock available? |
| Data Access | Database queries and persistence | Load a product by ID |
Putting an “is stock available?” check directly in a controller may appear convenient. However, the same rule may be needed by another controller, a background process, or a different endpoint. When the rule lives in a controller, duplication increases and changes become harder. With a service-based approach, the controller delegates the use case to the Business service.
Designing the service contract
The first step is to define the behavior required by the API through an interface in the Business layer. The interface makes the controller depend on a behavior contract rather than on a concrete implementation.
public interface IProductService
{
Task<ProductDto?> GetByIdAsync(int id, CancellationToken cancellationToken);
Task<IReadOnlyList<ProductDto>> GetActiveAsync(CancellationToken cancellationToken);
Task<ServiceResult<ProductDto>> CreateAsync(
CreateProductRequest request,
CancellationToken cancellationToken);
}The service returns a DTO instead of exposing the entity directly. This prevents the API from exposing every database field and keeps the external contract independent from the persistence model. A result wrapper such as ServiceResult<T> can provide a consistent way to represent successful and failed operations.
public sealed record ServiceError(string Code, string Message);
public sealed class ServiceResult<T>
{
public bool Succeeded { get; init; }
public T? Data { get; init; }
public IReadOnlyList<ServiceError> Errors { get; init; } = [];
public static ServiceResult<T> Success(T data) =>
new() { Succeeded = true, Data = data };
public static ServiceResult<T> Failure(params ServiceError[] errors) =>
new() { Succeeded = false, Errors = errors };
}A result wrapper is not mandatory. Some projects use custom exceptions for business failures, while others use validation libraries. The important point is that the API must be able to translate business outcomes into consistent HTTP responses.
Validation and business rules inside a service
Consider product creation. The product name must not be empty, the price must be greater than zero, and an active product with the same name must not already exist. Some rules can be expressed with attributes on the request DTO, but uniqueness requires a database query and belongs in the Business workflow.
public sealed class ProductService(
IProductRepository productRepository,
IUnitOfWork unitOfWork,
ILogger<ProductService> logger) : IProductService
{
public async Task<ServiceResult<ProductDto>> CreateAsync(
CreateProductRequest request,
CancellationToken cancellationToken)
{
var name = request.Name?.Trim();
if (string.IsNullOrWhiteSpace(name))
{
return ServiceResult<ProductDto>.Failure(
new("ProductNameRequired", "Product name is required."));
}
if (request.Price <= 0)
{
return ServiceResult<ProductDto>.Failure(
new("InvalidPrice", "Product price must be greater than zero."));
}
var exists = await productRepository.ExistsByNameAsync(
name, cancellationToken);
if (exists)
{
return ServiceResult<ProductDto>.Failure(
new("DuplicateProduct", "An active product with this name already exists."));
}
var product = new Product
{
Name = name,
Price = request.Price,
StockQuantity = request.StockQuantity,
IsActive = true
};
await productRepository.AddAsync(product, cancellationToken);
await unitOfWork.SaveChangesAsync(cancellationToken);
logger.LogInformation("Product {ProductId} created", product.Id);
return ServiceResult<ProductDto>.Success(ToDto(product));
}
private static ProductDto ToDto(Product product) => new(
product.Id,
product.Name,
product.Price,
product.StockQuantity,
product.IsActive);
}The workflow is intentionally explicit: normalize input, validate basic rules, perform the required database check, create the entity, add it through the repository, and persist it through the Unit of Work. The controller does not need to know these details.
Conditional operations and order creation
Business workflows often contain several conditions. When creating an order, the product must exist, be active, and have enough stock. Checking these conditions in a sensible order reduces unnecessary database operations and produces more useful errors.
public sealed class OrderService(
IProductRepository productRepository,
IOrderRepository orderRepository,
IUnitOfWork unitOfWork) : IOrderService
{
public async Task<ServiceResult<OrderDto>> CreateAsync(
CreateOrderRequest request,
CancellationToken cancellationToken)
{
if (request.ProductId <= 0 || request.Quantity <= 0)
{
return ServiceResult<OrderDto>.Failure(
new("InvalidOrder", "Product and quantity must be valid."));
}
var product = await productRepository.GetByIdAsync(
request.ProductId, cancellationToken);
if (product is null)
{
return ServiceResult<OrderDto>.Failure(
new("ProductNotFound", "The product was not found."));
}
if (!product.IsActive)
{
return ServiceResult<OrderDto>.Failure(
new("InactiveProduct", "Orders cannot be created for inactive products."));
}
if (product.StockQuantity < request.Quantity)
{
return ServiceResult<OrderDto>.Failure(
new("InsufficientStock", "There is not enough stock."));
}
var order = new Order
{
ProductId = product.Id,
Quantity = request.Quantity,
UnitPrice = product.Price,
CreatedAtUtc = DateTime.UtcNow,
Status = OrderStatus.Pending
};
product.StockQuantity -= request.Quantity;
orderRepository.Add(order);
await unitOfWork.SaveChangesAsync(cancellationToken);
return ServiceResult<OrderDto>.Success(ToDto(order));
}
private static OrderDto ToDto(Order order) => new(
order.Id,
order.ProductId,
order.Quantity,
order.UnitPrice,
order.Status.ToString());
}Reducing stock and adding the order are parts of one use case. If one change succeeds while the other fails, the data becomes inconsistent. Therefore, we must explicitly evaluate whether the workflow requires a transaction.
Defining transaction requirements
When the database provider supports transactions, Entity Framework Core applies changes from a single SaveChangesAsync call within a transaction. However, multiple save operations, multi-stage workflows, or multiple DbContexts may require an explicit transaction boundary.
The Unit of Work abstraction from the previous lesson can expose transaction coordination:
public interface IUnitOfWork
{
Task ExecuteInTransactionAsync(
Func<CancellationToken, Task> operation,
CancellationToken cancellationToken);
Task SaveChangesAsync(CancellationToken cancellationToken);
}The service can then coordinate the atomic operation:
public async Task<ServiceResult<OrderDto>> CreateAsync(
CreateOrderRequest request,
CancellationToken cancellationToken)
{
var product = await productRepository.GetByIdAsync(
request.ProductId, cancellationToken);
if (product is null || !product.IsActive)
{
return ServiceResult<OrderDto>.Failure(
new("ProductUnavailable", "The product is not available for ordering."));
}
if (product.StockQuantity < request.Quantity)
{
return ServiceResult<OrderDto>.Failure(
new("InsufficientStock", "There is not enough stock."));
}
var order = new Order
{
ProductId = product.Id,
Quantity = request.Quantity,
UnitPrice = product.Price,
CreatedAtUtc = DateTime.UtcNow,
Status = OrderStatus.Pending
};
await unitOfWork.ExecuteInTransactionAsync(async token =>
{
product.StockQuantity -= request.Quantity;
orderRepository.Add(order);
await unitOfWork.SaveChangesAsync(token);
}, cancellationToken);
return ServiceResult<OrderDto>.Success(ToDto(order));
}Using a transaction does not mean wrapping every service method in one. Use a transaction when several persistence operations must succeed or fail together. Avoid keeping long-running external service calls inside a database transaction because this can increase lock duration and resource consumption.
Data flow between the API and Business service
The API controller should translate the service result into HTTP status codes. The following controller contains no stock or product rules; it only receives the request and interprets the result.
[ApiController]
[Route("api/orders")]
public class OrdersController(IOrderService orderService) : ControllerBase
{
[HttpPost]
public async Task<ActionResult<OrderDto>> Create(
CreateOrderRequest request,
CancellationToken cancellationToken)
{
var result = await orderService.CreateAsync(
request, cancellationToken);
if (!result.Succeeded)
{
var firstError = result.Errors.First();
return firstError.Code switch
{
"ProductUnavailable" => NotFound(firstError),
"InsufficientStock" => Conflict(firstError),
_ => BadRequest(firstError)
};
}
return CreatedAtAction(
nameof(GetById),
new { id = result.Data!.Id },
result.Data);
}
[HttpGet("{id:int}")]
public async Task<ActionResult<OrderDto>> GetById(
int id,
CancellationToken cancellationToken)
{
var order = await orderService.GetByIdAsync(id, cancellationToken);
return order is null ? NotFound() : Ok(order);
}
}Part of input validation can be handled by [ApiController] and request DTO attributes. However, authorization, stock availability, existing records, and process-state rules must be checked in the Business layer. Client-side validation must never be treated as a security boundary.
Registering services with dependency injection
Constructor injection makes service dependencies explicit and improves testability. Register the Business and Data Access services in the API project’s Program.cs file.
builder.Services.AddScoped<IProductService, ProductService>();
builder.Services.AddScoped<IOrderService, OrderService>();
builder.Services.AddScoped<IProductRepository, ProductRepository>();
builder.Services.AddScoped<IOrderRepository, OrderRepository>();
builder.Services.AddScoped<IUnitOfWork, EfUnitOfWork>();Scoped is commonly appropriate for services and repositories that use a scoped DbContext. It allows components in the same HTTP request to share the expected scope. Registering a singleton service that depends on a scoped DbContext or repository is an invalid lifetime relationship.
Common mistakes
- Putting business rules in controllers: Rules become duplicated across endpoints and controllers grow beyond their HTTP responsibility.
- Making repositories own workflows: Repositories should provide data access; reserving stock or changing order state belongs to the Business layer.
- Returning entities directly: This may expose unwanted fields and couple the API contract to the database model.
- Choosing the wrong transaction boundary: Unnecessary transactions add complexity, while separate saves for one atomic workflow can create inconsistent data.
- Trusting client-side validation: Client checks can be bypassed. Critical rules must be enforced on the server.
- Throwing a generic exception for every business failure: Expected rule violations can be represented as controlled results; exceptions are better suited to unexpected or technical failures.
- Creating static or global services: This reduces the benefits of dependency injection and makes unit testing more difficult.
Short practice exercise
Design a CancelOrderAsync method. It must apply the following rules:
- Return an appropriate error if the order does not exist.
- Only orders in the
Pendingstate can be cancelled. - Increase the product stock by the cancelled order quantity.
- Persist the order-state change and stock update within the same transaction.
- Return
204 No Contentfor success and409 Conflictwhen the order is in an invalid state.
Test the workflow with a missing order, a completed order, and a pending order. Also examine whether data remains consistent when two requests attempt to consume the last available units at nearly the same time.
Conclusion
The Business layer is the part of the application that makes decisions rather than merely moving data. Service classes centralize validation, conditional operations, entity mapping, and transaction boundaries. Controllers become smaller, repositories remain focused on persistence, and use cases become easier to verify with unit tests.
The overall flow can now be described as follows: the API receives a request and passes its DTO to a Business service; the service evaluates the rules, uses Repository and Unit of Work abstractions, and returns a result that the API converts into an HTTP response. In the next stage, we will expose these services through more complete REST endpoints and refine the design of HTTP contracts.
Sources
- https://learn.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-10.0
- https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/dependency-injection?view=aspnetcore-10.0
- https://learn.microsoft.com/en-us/aspnet/core/mvc/models/validation?view=aspnetcore-7.0
- https://learn.microsoft.com/en-us/ef/core/saving/transactions