Introduction
In the previous lessons, we created the core entities, value objects, enums, and business constraints in the Domain layer. That layer explains what the business is and which rules must always remain valid. We have not yet organized the application workflows that allow a user to list products, view product details, or create a new product.
Those workflows belong in the Application layer. The Application layer represents the system’s use cases: meaningful actions that the application can perform. It coordinates the workflow without depending directly on HTTP, SQL Server, Entity Framework Core, Swagger, or any other external technology.
We will also introduce Data Transfer Objects, commonly called DTOs. A DTO defines the shape of data exchanged between boundaries. Instead of exposing a persistence entity directly through an API, we will create request and response models that are designed for specific operations.
In a Clean Architecture design, the application core can contain entities, interfaces, services, and infrastructure-independent DTOs. Outer layers depend on this core; the core should not depend on Infrastructure or Presentation. This direction keeps use cases easier to test and protects business workflows from technical implementation details.
Responsibilities of the Application layer
The Application layer should not become a second controller layer or a place where every database query is written. Its responsibility is to describe and coordinate application behavior in an explicit, testable way.
- Define use cases: Examples include listing products, retrieving a product by ID, and creating a product.
- Coordinate workflows: A use case can load data, invoke domain behavior, save changes, and map the result to a response DTO.
- Depend on abstractions: The layer requests the capabilities it needs through repository or service contracts instead of depending on a concrete database implementation.
- Define data boundaries: Request and response DTOs make the accepted and returned data explicit.
- Support testing: A use case can be tested with a fake repository instead of requiring a live SQL Server database.
The Application layer is not responsible for route templates, HTTP status codes, or controller binding. Those concerns belong to Presentation. Similarly, the Application layer should not directly use DbContext. That dependency would couple the use cases to EF Core and make infrastructure details part of the application core.
Feature-oriented organization
Putting every DTO in one global folder and every service in another can work in a small project, but it becomes difficult to navigate as the solution grows. A feature-oriented structure keeps files related to the same business capability together.
Application
├── Products
│ ├── DTOs
│ │ ├── CreateProductRequest.cs
│ │ ├── ProductResponse.cs
│ │ └── ProductListItemResponse.cs
│ ├── Interfaces
│ │ └── IProductRepository.cs
│ └── Services
│ └── ProductService.cs
└── Common
└── Result.csThis structure groups the Product use cases in one area. Another valid approach is to organize one folder per use case, such as Products/CreateProduct and Products/GetProductById. The folder naming is less important than keeping responsibilities and dependencies clear.
Request and response DTOs
An entity is part of the persistent domain model. A DTO is a data carrier designed for a particular boundary or operation. For that reason, using one ProductDto for creation, listing, updating, and detail responses is usually too broad.
When a client creates a product, it should not provide the product ID, creation timestamp, or internal status unless the business explicitly allows it. These values should be generated or controlled by the application and domain rules.
namespace CleanShop.Application.Products.DTOs;
public sealed record CreateProductRequest(
string Name,
decimal Price,
int StockQuantity,
int CategoryId
);
public sealed record ProductResponse(
int Id,
string Name,
decimal Price,
int StockQuantity,
int CategoryId,
bool IsActive
);
public sealed record ProductListItemResponse(
int Id,
string Name,
decimal Price,
bool IsActive
);CreateProductRequest contains only the values accepted during creation. ProductResponse is suitable for a detail response, while ProductListItemResponse carries a smaller payload for a list screen.
When designing a DTO, ask the following questions:
- Should the client really be allowed to send this property?
- Is the property sensitive or intended only for administrators?
- Would returning it for every list item unnecessarily increase the payload?
- Should related entities or navigation properties be exposed?
- Does this DTO serve one specific use case or several unrelated operations?
Keeping entities separate from DTOs
Returning an entity directly from an API creates a strong coupling between the persistence model and the public API contract. A property added to the entity may unintentionally become part of the API response. Navigation properties can also produce circular JSON graphs, large payloads, or unexpected database queries.
There is also a security concern. An entity may contain fields such as InternalNote, CreatedByUserId, or administrative flags. Serializing the entity directly can expose information that was never intended for the client. On the input side, binding an incoming request directly to an entity may allow the client to submit fields it should not control. This is commonly known as over-posting.
Use explicit mapping instead:
public static class ProductMappings
{
public static ProductResponse ToResponse(Product product)
{
return new ProductResponse(
product.Id,
product.Name,
product.Price,
product.StockQuantity,
product.CategoryId,
product.IsActive);
}
public static ProductListItemResponse ToListItem(Product product)
{
return new ProductListItemResponse(
product.Id,
product.Name,
product.Price,
product.IsActive);
}
}The Domain entity is used internally, but the value returned across the application boundary is a DTO. Keeping mapping in a dedicated class makes the use case service easier to read and makes exposed fields easy to review.
Repository contracts and application services
The Application layer may need data, but it should not know whether that data comes from SQL Server, an in-memory fake, or another source. We therefore define the required contract in the Application project. Infrastructure will provide the implementation later.
using CleanShop.Domain.Entities;
namespace CleanShop.Application.Products.Interfaces;
public interface IProductRepository
{
Task GetByIdAsync(int id, CancellationToken cancellationToken);
Task GetActiveAsync(CancellationToken cancellationToken);
Task AddAsync(Product product, CancellationToken cancellationToken);
} Now we can create a service that coordinates the Product use cases:
using CleanShop.Application.Products.DTOs;
using CleanShop.Application.Products.Interfaces;
using CleanShop.Domain.Entities;
namespace CleanShop.Application.Products.Services;
public sealed class ProductService(IProductRepository productRepository)
{
public async Task<IReadOnlyList<ProductListItemResponse>> GetActiveAsync(
CancellationToken cancellationToken)
{
var products = await productRepository.GetActiveAsync(cancellationToken);
return products
.Select(ProductMappings.ToListItem)
.ToList();
}
public async Task<ProductResponse> CreateAsync(
CreateProductRequest request,
CancellationToken cancellationToken)
{
var product = Product.Create(
request.Name,
request.Price,
request.StockQuantity,
request.CategoryId);
await productRepository.AddAsync(product, cancellationToken);
return ProductMappings.ToResponse(product);
}
}The call to Product.Create is important. The Application service coordinates the workflow, while the Domain entity remains responsible for its own invariants, such as valid names, prices, or stock quantities.
Input and output contracts for use cases
Every use case should have a clear input and output contract. For example:
| Use case | Input | Output |
|---|---|---|
| List active products | Optional filters and paging data | List of ProductListItemResponse |
| Get product by ID | ProductId | ProductResponse or not-found result |
| Create product | CreateProductRequest | Created ProductResponse |
This makes communication between the controller and the Application service explicit. The controller binds the HTTP request to a DTO, invokes the use case, and converts the result into an HTTP response. The same use case could later be called by a background job, message consumer, or another entry point.
Common mistakes
- Returning entities directly: This couples the public API to the persistence model and may expose internal fields.
- Using one DTO for everything: Creation, update, listing, and detail operations usually have different requirements.
- Putting workflows in controllers: Controllers become difficult to test and the same rules get duplicated across entry points.
- Using DbContext in Application: This couples use cases to EF Core and SQL Server details.
- Including navigation properties in DTOs without a purpose: This can cause circular references, excessive queries, and unnecessarily large JSON responses.
- Ignoring mapping: Mapping libraries can be useful, but explicit mapping is often easier to review for security-sensitive or important contracts.
- Confusing validation with domain rules: Request shape validation belongs near the request boundary, while business invariants must remain protected by the Domain model.
Practice exercise
Extend the Product use case structure from this lesson:
- Add a
GetProductByIdmethod that returns aProductResponse. - Choose a not-found approach, such as a
NotFoundExceptionor an explicit result model. - Create an
UpdateProductRequestcontaining only properties that are allowed to change. - Add a query DTO containing search text and page information for product listing.
- Verify that every use case returns DTOs rather than exposing Domain entities.
You do not need to fully implement the Presentation layer yet. Focus on making the Application contracts understandable and ensuring that the Domain rules cannot be bypassed through the DTO design.
Conclusion
In this lesson, we positioned the Application layer as the part of the system that organizes use cases while remaining independent of external technologies. Request DTOs limit accepted input, response DTOs control the public output model, and explicit mapping separates the persistent entity from the API contract.
In the next stage, we will implement these contracts through repositories and Entity Framework Core in the Infrastructure layer. Because the abstractions were defined in the Application layer, the use cases can continue to work without knowing whether the data is stored in SQL Server or accessed through another implementation.
Sources
- https://learn.microsoft.com/en-us/dotnet/architecture/modern-web-apps-azure/common-web-application-architectures
- https://learn.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-10.0
- https://learn.microsoft.com/en-us/aspnet/web-api/overview/data/using-web-api-with-entity-framework/part-5
- https://learn.microsoft.com/en-us/ef/core/modeling/entity-types