LESSON 6 OF 22

6. Defining Repository and Application Service Contracts

Learn how to define repository and application service interfaces in the Application layer while separating data access from use-case orchestration.

25 dk 99

Introduction

In the previous lesson, we designed use cases and DTOs in the Application layer. In this lesson, we will explicitly define the dependencies required by those use cases. We will add repository and application service contracts, represented by interfaces, to the Application layer.

The primary goal is to prevent the Application layer from depending directly on Entity Framework Core, SQL Server, or a specific data-access class. The Application layer should know which behaviors it needs, but not how those behaviors are implemented. This approach follows the Dependency Inversion Principle.

Our example assumes a product-management project. The Product entity has already been created in the Domain layer, and product creation and listing DTOs already exist in the Application layer.

Repository and Application Service Responsibilities

What is a repository?

A repository abstracts the process of reading domain objects and aggregates from a persistence source and storing changes back to that source. A repository contract defines the data-access operations that are required, but does not contain SQL queries, DbContext usage, or table-mapping details.

For example, IProductRepository can define the operations needed to find, add, or remove products. Its EF Core implementation will be created later in the Infrastructure layer.

What is an application service?

An application service coordinates the flow of a use case. It can receive DTOs, read data through repositories, invoke domain behavior, coordinate multiple repository operations, and create response DTOs.

An application service must not replace the entity as the owner of business rules. Fundamental domain rules remain in the Domain layer. The application service orchestrates the steps through which a request must pass.

ComponentPrimary responsibilityShould not know about
RepositoryReading, adding, updating, and removing dataHTTP, DTO mapping, and use-case orchestration
Application serviceCoordinating a use case and mapping DTOsSQL, table names, and EF Core details
Domain entityProtecting business rules and valid stateDatabase connections and HTTP
InfrastructureProviding technical implementations of contractsAPI-specific presentation concerns

Placing Interfaces in the Application Layer

Interfaces can be grouped according to their purpose. The following structure is a readable and maintainable starting point for a growing project:

src/
  Application/
    Abstractions/
      Persistence/
        IProductRepository.cs
        IUnitOfWork.cs
      Services/
        IProductService.cs
    Products/
      Dtos/
        CreateProductRequest.cs
        ProductResponse.cs
      Services/
        ProductService.cs

Another option is to keep repository interfaces in a Repositories folder and application service interfaces in a Services folder. The folder name is less important than keeping the contracts in the Application layer and preserving the correct dependency direction.

Step 1: Define the Repository Contract

First, let us identify the data-access operations required for products. It is healthier to add only the operations required by existing use cases. Filling one generic repository with every possible operation can create large interfaces and unnecessary dependencies.

using CleanArchitecture.Domain.Entities;

namespace CleanArchitecture.Application.Abstractions.Persistence;

public interface IProductRepository
{
    Task<Product?> GetByIdAsync(
        Guid id,
        CancellationToken cancellationToken = default);

    Task<IReadOnlyList<Product>> GetAllAsync(
        CancellationToken cancellationToken = default);

    Task AddAsync(
        Product product,
        CancellationToken cancellationToken = default);

    void Remove(Product product);
}

Several details matter here. The Task return types support asynchronous data access. CancellationToken allows a database operation to stop when the request is cancelled. GetByIdAsync can return null when no record exists, so its return type is nullable.

AddAsync may add the entity to the repository’s tracked set. If a unit-of-work approach is used, the actual persistence operation can be controlled through SaveChangesAsync or IUnitOfWork. This separation helps complete multiple changes within one transaction.

Step 2: Define the Unit of Work Contract

A separate IUnitOfWork is not mandatory in every project. However, if a use case changes data through multiple repositories, a separate persistence abstraction can make the commit boundary explicit.

namespace CleanArchitecture.Application.Abstractions.Persistence;

public interface IUnitOfWork
{
    Task<int> SaveChangesAsync(
        CancellationToken cancellationToken = default);
}

This interface prevents the Application layer from knowing how a transaction or an EF Core DbContext works. An Infrastructure implementation can connect the contract to DbContext.SaveChangesAsync.

Step 3: Define the Application Service Contract

Now we can add an application service contract representing product use cases. This interface determines which methods a controller in the Presentation layer can call to execute application workflows.

using CleanArchitecture.Application.Products.Dtos;

namespace CleanArchitecture.Application.Abstractions.Services;

public interface IProductService
{
    Task<ProductResponse?> GetByIdAsync(
        Guid id,
        CancellationToken cancellationToken = default);

    Task<IReadOnlyList<ProductResponse>> GetAllAsync(
        CancellationToken cancellationToken = default);

    Task<ProductResponse> CreateAsync(
        CreateProductRequest request,
        CancellationToken cancellationToken = default);

    Task DeleteAsync(
        Guid id,
        CancellationToken cancellationToken = default);
}

The repository’s Product entity is not exposed by this contract. Instead, response DTOs are returned. This prevents the Presentation layer from becoming dependent on the internal structure of the domain entity. It also makes it easier to change response field names, calculated values, or API-specific data later.

Step 4: Make the Service Depend on Contracts

The application service should receive dependencies through interfaces only. In the following example, ProductService does not directly use ProductRepository or AppDbContext.

using CleanArchitecture.Application.Abstractions.Persistence;
using CleanArchitecture.Application.Abstractions.Services;
using CleanArchitecture.Application.Products.Dtos;
using CleanArchitecture.Domain.Entities;

namespace CleanArchitecture.Application.Products.Services;

public sealed class ProductService(
    IProductRepository productRepository,
    IUnitOfWork unitOfWork) : IProductService
{
    public async Task<ProductResponse?> GetByIdAsync(
        Guid id,
        CancellationToken cancellationToken = default)
    {
        var product = await productRepository
            .GetByIdAsync(id, cancellationToken);

        return product is null
            ? null
            : ToResponse(product);
    }

    public async Task<IReadOnlyList<ProductResponse>> GetAllAsync(
        CancellationToken cancellationToken = default)
    {
        var products = await productRepository
            .GetAllAsync(cancellationToken);

        return products.Select(ToResponse).ToList();
    }

    public async Task<ProductResponse> CreateAsync(
        CreateProductRequest request,
        CancellationToken cancellationToken = default)
    {
        var product = Product.Create(
            request.Name,
            request.Description,
            request.Price);

        await productRepository.AddAsync(product, cancellationToken);
        await unitOfWork.SaveChangesAsync(cancellationToken);

        return ToResponse(product);
    }

    public async Task DeleteAsync(
        Guid id,
        CancellationToken cancellationToken = default)
    {
        var product = await productRepository
            .GetByIdAsync(id, cancellationToken);

        if (product is null)
        {
            throw new KeyNotFoundException("Product was not found.");
        }

        productRepository.Remove(product);
        await unitOfWork.SaveChangesAsync(cancellationToken);
    }

    private static ProductResponse ToResponse(Product product) =>
        new(product.Id, product.Name, product.Description, product.Price);
}

The call to Product.Create allows the domain entity to protect its own rules. The service only transfers request data to the domain factory method. Whether a missing product should produce an exception or a dedicated result type should follow the project’s error-handling standard. Centralized exception handling in a later lesson will make this decision more consistent.

Step 5: Prepare the Infrastructure Implementation

The Application project contains only the contracts. The concrete implementation belongs in Infrastructure:

public sealed class ProductRepository(AppDbContext dbContext)
    : IProductRepository
{
    public async Task<Product?> GetByIdAsync(
        Guid id,
        CancellationToken cancellationToken = default)
    {
        return await dbContext.Products
            .FirstOrDefaultAsync(x => x.Id == id, cancellationToken);
    }

    public async Task<IReadOnlyList<Product>> GetAllAsync(
        CancellationToken cancellationToken = default)
    {
        return await dbContext.Products
            .AsNoTracking()
            .OrderBy(x => x.Name)
            .ToListAsync(cancellationToken);
    }

    public Task AddAsync(
        Product product,
        CancellationToken cancellationToken = default)
    {
        return dbContext.Products.AddAsync(product, cancellationToken).AsTask();
    }

    public void Remove(Product product) => dbContext.Products.Remove(product);
}

public sealed class EfUnitOfWork(AppDbContext dbContext) : IUnitOfWork
{
    public Task<int> SaveChangesAsync(
        CancellationToken cancellationToken = default)
    {
        return dbContext.SaveChangesAsync(cancellationToken);
    }
}

Because this code belongs to Infrastructure, the Application project does not need to know about EF Core APIs. Infrastructure references Application; Application does not reference Infrastructure. The dependency direction therefore remains pointed toward the inner layers.

Step 6: Register Dependencies with Dependency Injection

Concrete implementations can be registered in the composition root, which is normally the Presentation/API project, or through an extension method supplied by Infrastructure.

public static IServiceCollection AddInfrastructure(
    this IServiceCollection services,
    IConfiguration configuration)
{
    services.AddDbContext<AppDbContext>(options =>
        options.UseSqlServer(
            configuration.GetConnectionString("DefaultConnection")));

    services.AddScoped<IProductRepository, ProductRepository>();
    services.AddScoped<IUnitOfWork, EfUnitOfWork>();

    return services;
}

public static IServiceCollection AddApplication(
    this IServiceCollection services)
{
    services.AddScoped<IProductService, ProductService>();
    return services;
}

In web applications, an EF Core DbContext is usually registered with a scoped lifetime. A scoped lifetime is also a suitable starting point for the repository and application service that use it. A singleton service depending on a scoped DbContext creates a lifetime mismatch and can cause incorrect state sharing.

Common Mistakes

  • Adding DbContext to the Application layer: This couples the use case to a persistence technology and makes testing harder.
  • Returning entities from controllers: The domain model becomes the API contract and clients become dependent on internal structure.
  • Making a generic repository too large: Requiring every entity to expose the same CRUD operations weakens need-driven interface design.
  • Managing workflows inside repositories: Coordinating calls to multiple repositories is the responsibility of the application service.
  • Adding every possible interface automatically: Add an abstraction when there is a genuine variation point or testing need.
  • Choosing the wrong lifetime: Avoid placing scoped EF Core dependencies inside singleton services.
  • Ignoring CancellationToken: Passing cancellation signals to lower layers improves resource usage during long-running operations.

Short Practice Exercise

Complete the following exercise:

  1. Add a FindByNameAsync method to IProductRepository.
  2. Add a method to IProductService representing the product-search use case.
  3. Implement the method so that it returns a list of ProductResponse objects.
  4. Create an EF Core query in Infrastructure while leaving case-sensitivity behavior to the database provider and its configured collation.
  5. Design a unit-test scenario using mock or fake implementations of the repository and service contracts.

Conclusion

In this lesson, we saw how the Application layer can work without knowing persistence details. Repository contracts represent data-access operations, while application service contracts represent use cases. Concrete implementations belong to Infrastructure, and Dependency Injection connects the pieces at runtime.

In the next lesson, we will implement these contracts in the Infrastructure layer with Entity Framework Core and add database connectivity without breaking the dependency direction.

Sources