Introduction
In the previous lessons, we covered endpoint design, CRUD operations, validation, centralized error handling, and related resources. As an application grows, an important architectural problem appears: controllers become increasingly large, Entity Framework Core queries become mixed with HTTP details, and the same business rules start to be repeated across multiple endpoints.
In this lesson, we will organize the request flow more clearly. The goal is to keep the controller as a thin layer that receives an HTTP request and converts the result into an HTTP response. Business rules will live in application services, while data access will be organized through repositories or dedicated query components. This makes the code easier to test, reduces the impact of changes, and clarifies each component’s responsibilities.
Our examples use a Product resource. The same approach can be applied to orders, customers, categories, or the related resources discussed earlier.
Responsibilities of the layers
Controller layer
The controller is responsible for HTTP-specific work: receiving route parameters, passing the request model to a service, returning the appropriate status code, and producing a response DTO when necessary. Database queries, complex price calculations, and business rules should not be implemented in the controller.
Application service
An application service represents a use case. For example, CreateProductAsync, GetProductAsync, and ArchiveProductAsync can each represent an application operation. The service coordinates repositories, domain rules, transaction boundaries, and DTO mapping.
Repository or data-access component
A repository hides data-source details. In an Entity Framework Core application, a repository may execute queries through DbContext. However, creating an automatic repository for every table is not mandatory. For simple queries, using DbContext directly in an application service can be reasonable, while complex or reused data-access operations are often easier to maintain in a separate component.
The important point is not to increase the number of classes unnecessarily, but to separate responsibilities and identify meaningful points of change.
Example project structure
You do not have to split the application into multiple projects immediately. A folder-based structure is sufficient at the beginning:
Api/Controllers/ProductsController.cs Application/Products/IProductService.cs Application/Products/ProductService.cs Application/Products/ProductDtos.cs Infrastructure/Repositories/IProductRepository.cs Infrastructure/Repositories/ProductRepository.cs Infrastructure/Persistence/AppDbContext.cs Domain/Entities/Product.cs
In larger systems, these folders can be moved into separate class library projects. For example, the Domain project can avoid references to ASP.NET Core and EF Core; Infrastructure can contain database implementations; and Api can remain the HTTP entry point.
Defining the repository interface
First, define the behavior expected by the application service. The interface should express what the application needs rather than exposing EF Core itself.
public interface IProductRepository { Task<Product?> GetByIdAsync(Guid id, CancellationToken cancellationToken); Task<bool> ExistsBySkuAsync(string sku, CancellationToken cancellationToken); Task AddAsync(Product product, CancellationToken cancellationToken); Task SaveChangesAsync(CancellationToken cancellationToken); }
Adding a CancellationToken to repository methods helps stop database operations when the client disconnects or the request is cancelled. In a real project, list operations should also model filtering, sorting, and pagination requirements explicitly.
Implementing the EF Core repository
The repository implementation uses DbContext. For read-only queries, AsNoTracking can reduce unnecessary change-tracking overhead.
public sealed class ProductRepository(AppDbContext dbContext) : IProductRepository { public Task<Product?> GetByIdAsync( Guid id, CancellationToken cancellationToken) => dbContext.Products .AsNoTracking() .SingleOrDefaultAsync(x => x.Id == id, cancellationToken); public Task<bool> ExistsBySkuAsync( string sku, CancellationToken cancellationToken) => dbContext.Products .AnyAsync(x => x.Sku == sku, cancellationToken); public Task AddAsync( Product product, CancellationToken cancellationToken) { dbContext.Products.Add(product); return Task.CompletedTask; } public Task SaveChangesAsync(CancellationToken cancellationToken) => dbContext.SaveChangesAsync(cancellationToken); }
Here, AddAsync only adds the entity to the change tracker; persistence occurs when SaveChangesAsync is called. In larger operations, multiple repositories may need to use the same DbContext and save within a single transaction boundary.
Creating the application service
The service interface is the application contract used by outer layers:
public interface IProductService { Task<ProductResponse?> GetAsync( Guid id, CancellationToken cancellationToken); Task<ProductResponse> CreateAsync( CreateProductRequest request, CancellationToken cancellationToken); }
DTOs form the external API contract. Instead of returning an entity directly, create a response DTO in the service. This prevents the database model from leaking into the client contract, avoids exposing unnecessary fields, and reduces the effect of future schema changes.
public sealed class ProductService( IProductRepository repository, TimeProvider timeProvider) : IProductService { public async Task<ProductResponse?> GetAsync( Guid id, CancellationToken cancellationToken) { var product = await repository.GetByIdAsync(id, cancellationToken); return product is null ? null : new ProductResponse( product.Id, product.Name, product.Sku, product.Price, product.CreatedAtUtc); } public async Task<ProductResponse> CreateAsync( CreateProductRequest request, CancellationToken cancellationToken) { if (await repository.ExistsBySkuAsync( request.Sku, cancellationToken)) { throw new ConflictException("The SKU is already in use."); } var product = new Product { Id = Guid.NewGuid(), Name = request.Name.Trim(), Sku = request.Sku.Trim().ToUpperInvariant(), Price = request.Price, CreatedAtUtc = timeProvider.GetUtcNow().UtcDateTime }; await repository.AddAsync(product, cancellationToken); await repository.SaveChangesAsync(cancellationToken); return new ProductResponse( product.Id, product.Name, product.Sku, product.Price, product.CreatedAtUtc); } }
Here, SKU uniqueness is checked as a business rule in the service. A unique index should also exist in the database. The application check provides a clearer user-facing error, while the database constraint remains the final protection against concurrent requests.
Simplifying the controller
Once the service is ready, the controller only coordinates the HTTP flow:
[ApiController] [Route("api/products")] public sealed class ProductsController(IProductService productService) : ControllerBase { [HttpGet("{id:guid}")] public async Task<ActionResult<ProductResponse>> Get( Guid id, CancellationToken cancellationToken) { var product = await productService.GetAsync(id, cancellationToken); return product is null ? NotFound() : Ok(product); } [HttpPost] public async Task<ActionResult<ProductResponse>> Create( CreateProductRequest request, CancellationToken cancellationToken) { var product = await productService.CreateAsync( request, cancellationToken); return CreatedAtAction( nameof(Get), new { id = product.Id }, product); } }
The controller no longer depends on a repository, DbContext, or several infrastructure services. When validation fails, [ApiController] behavior handles the request automatically. When the service reports a missing resource or a business-rule violation, centralized error handling can produce the appropriate ProblemDetails response.
Registering dependencies
ASP.NET Core’s built-in dependency injection container maps interfaces to implementations:
builder.Services.AddDbContext<AppDbContext>(options => options.UseSqlServer( builder.Configuration.GetConnectionString("Default"))); builder.Services.AddScoped<IProductRepository, ProductRepository>(); builder.Services.AddScoped<IProductService, ProductService>(); builder.Services.AddSingleton(TimeProvider.System);
DbContext is registered with a scoped lifetime by default in web applications. Making the repository and application service scoped as well allows them to use the same scoped DbContext during one HTTP request. A singleton service should not receive a scoped DbContext dependency; this creates a lifetime mismatch and unsafe sharing.
You can group registrations in extension methods:
public static class ServiceCollectionExtensions { public static IServiceCollection AddApplicationServices( this IServiceCollection services) { services.AddScoped<IProductService, ProductService>(); return services; } public static IServiceCollection AddInfrastructureServices( this IServiceCollection services, IConfiguration configuration) { services.AddDbContext<AppDbContext>(options => options.UseSqlServer( configuration.GetConnectionString("Default"))); services.AddScoped<IProductRepository, ProductRepository>(); return services; } }builder.Services .AddApplicationServices() .AddInfrastructureServices(builder.Configuration);
Improving testability
Because the service depends on interfaces, unit tests do not need a real SQL Server. A fake repository can be supplied to test duplicate SKU and successful creation scenarios in isolation. This keeps business-logic tests fast. Separate integration tests should verify EF Core mappings, real queries, and middleware behavior.
To improve testability, avoid static clocks, static configuration, and infrastructure objects created directly with new inside the service. Provide these as constructor dependencies instead. However, the goal is not to mock every class; abstract components that genuinely vary or depend on external systems.
Common mistakes
- Fat controllers: Combining queries, mapping, business rules, and transaction management in the controller.
- Returning entities directly: Publishing database fields without converting them into an API contract.
- Creating a repository for everything: Adding abstractions that only repeat DbSet methods and provide no useful behavior.
- Incorrect lifetimes: Injecting a DbContext or scoped service into a singleton.
- Ignoring cancellation: Failing to pass request cancellation to long-running database queries.
- Trusting only application checks: Omitting a database index for critical rules such as uniqueness.
- Overusing generic services: Forcing different business rules into one overly generic CRUD service.
Short practice exercise
- Create ICategoryRepository and ICategoryService interfaces.
- Add a repository method that searches by category name.
- Prevent duplicate category names in the application service.
- Remove the DbContext dependency from the controller.
- Register the service and repository in the DI container.
- Write tests for successful creation, duplicate names, and a missing category.
Conclusion
Separating repositories, services, and application layers is more than arranging folders. It means defining each layer’s responsibility, managing dependencies through interfaces, and keeping HTTP concerns separate from business logic. A simpler controller, use-case-oriented services, and controlled EF Core access improve testability, maintainability, and resilience to change.
In later lessons, pagination, filtering, sorting, and more advanced query models can be added on top of this structure. When the boundaries are clear, these capabilities can be implemented without turning the controller into another large class.