Introduction
In the previous lesson, we prepared migrations, the SQL Server connection, and seed data. In this lesson, we will write the code that actually accesses the database. Repository contracts defined in the Application layer will be implemented in the Infrastructure layer with Entity Framework Core. Higher layers will therefore use data-access capabilities without knowing about DbContext, SQL Server, or EF Core-specific details.
The objective is not simply to write CRUD methods. We also need to understand which responsibilities belong to a repository, which belong to an application service, where SaveChangesAsync should be called, and when the Unit of Work approach is useful without creating unnecessary abstraction.
Repository and Unit of Work Responsibilities
In Clean Architecture, the Application layer defines the contract it needs. It does not decide how data access is implemented. The Infrastructure layer provides the EF Core implementation.
| Component | Responsibility | Should not know about |
|---|---|---|
| Repository contract | Define required queries and commands for an entity | EF Core, SQL Server, and table details |
| Repository implementation | Execute LINQ queries and persistence operations | HTTP, controllers, and user interfaces |
| Unit of Work | Commit changes belonging to one operation together | The business rule itself |
| Application service | Orchestrate the use-case flow | How SQL is generated |
In EF Core, the DbContext naturally acts as a Unit of Work: it tracks changes and persists them when SaveChangesAsync is called. Therefore, every project does not need a complex transaction framework. In a straightforward use case, an application service can use one or more repositories and call SaveChangesAsync once at the end.
1. Reviewing the Repository Contracts
Assume that the contracts created in the earlier lesson look like the following. Names can be adapted to the entities in your project; the important point is the dependency direction.
public interface IOrderRepository
{
Task<Order?> GetByIdAsync(Guid id, CancellationToken cancellationToken = default);
Task<IReadOnlyList<Order>> GetByCustomerAsync(
Guid customerId,
CancellationToken cancellationToken = default);
Task AddAsync(Order order, CancellationToken cancellationToken = default);
void Update(Order order);
void Remove(Order order);
}
public interface IUnitOfWork
{
Task<int> SaveChangesAsync(CancellationToken cancellationToken = default);
}AddAsync does not immediately send an INSERT statement to the database. It places the entity under the context's change tracking system. The actual persistence happens when the use case calls SaveChangesAsync through the Unit of Work. This distinction allows several repositories to contribute changes to the same operation.
2. Using DbContext as the Unit of Work
The Infrastructure-layer DbContext is the shared persistence component used by the repositories. The context can implement the IUnitOfWork contract directly.
public sealed class ApplicationDbContext : DbContext, IUnitOfWork
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public DbSet<Order> Orders => Set<Order>();
public DbSet<Customer> Customers => Set<Customer>();
public Task<int> SaveChangesAsync(
CancellationToken cancellationToken = default)
{
return base.SaveChangesAsync(cancellationToken);
}
}The Application layer sees only IUnitOfWork, while the EF Core reference remains in Infrastructure. In ASP.NET Core, a DbContext is commonly registered with a scoped lifetime. This usually provides one context per HTTP request, allowing repositories used within that request to share the same change tracker and Unit of Work scope.
3. Implementing the Repository
Now implement IOrderRepository in the Infrastructure layer.
internal sealed class OrderRepository : IOrderRepository
{
private readonly ApplicationDbContext _context;
public OrderRepository(ApplicationDbContext context)
{
_context = context;
}
public async Task<Order?> GetByIdAsync(
Guid id,
CancellationToken cancellationToken = default)
{
return await _context.Orders
.Include(order => order.Items)
.SingleOrDefaultAsync(
order => order.Id == id,
cancellationToken);
}
public async Task<IReadOnlyList<Order>> GetByCustomerAsync(
Guid customerId,
CancellationToken cancellationToken = default)
{
return await _context.Orders
.AsNoTracking()
.Where(order => order.CustomerId == customerId)
.OrderByDescending(order => order.CreatedAt)
.ToListAsync(cancellationToken);
}
public async Task AddAsync(
Order order,
CancellationToken cancellationToken = default)
{
await _context.Orders.AddAsync(order, cancellationToken);
}
public void Update(Order order)
{
_context.Orders.Update(order);
}
public void Remove(Order order)
{
_context.Orders.Remove(order);
}
}GetByIdAsync uses Include because the order-detail use case needs the order items. In a read-only list query, AsNoTracking is often appropriate because the returned objects will not be modified and saved. Tracking is useful when an entity will be changed; no-tracking can reduce change-tracking overhead for read-only scenarios.
Notice that the repository does not call SaveChangesAsync. Its responsibility is to query, add, update, or remove entities. The application use case decides when the complete operation should be committed.
4. Using CRUD Operations in the Application Layer
A create-order use case can coordinate the repository and Unit of Work as follows:
public sealed class CreateOrderHandler
{
private readonly IOrderRepository _orders;
private readonly IUnitOfWork _unitOfWork;
public CreateOrderHandler(
IOrderRepository orders,
IUnitOfWork unitOfWork)
{
_orders = orders;
_unitOfWork = unitOfWork;
}
public async Task<Guid> HandleAsync(
CreateOrderCommand command,
CancellationToken cancellationToken)
{
var order = Order.Create(
command.CustomerId,
command.Items);
await _orders.AddAsync(order, cancellationToken);
await _unitOfWork.SaveChangesAsync(cancellationToken);
return order.Id;
}
}The flow is explicit and testable: receive the command, create the domain entity, add it through the repository, and commit through the Unit of Work. Business rules remain in domain behavior such as Order.Create; the repository remains focused on persistence.
When updating an entity that was loaded with tracking, calling Update again is often unnecessary:
var order = await _orders.GetByIdAsync(id, cancellationToken);
if (order is null)
{
throw new NotFoundException("Order was not found.");
}
order.ChangeShippingAddress(command.Address);
await _unitOfWork.SaveChangesAsync(cancellationToken);Because the entity is tracked by the same DbContext, EF Core detects the changed state. If an entity was loaded with no tracking, its update behavior must be handled deliberately using attach or update operations. Otherwise, you may update more properties than intended or encounter state-management problems.
5. Dependency Injection Registration
Repository implementations should be registered at the Composition Root, usually the API or Presentation project. Infrastructure can expose an extension method for its registrations:
public static class InfrastructureServiceRegistration
{
public static IServiceCollection AddInfrastructure(
this IServiceCollection services,
IConfiguration configuration)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
configuration.GetConnectionString("DefaultConnection")));
services.AddScoped<IUnitOfWork>(
provider => provider.GetRequiredService<ApplicationDbContext>());
services.AddScoped<IOrderRepository, OrderRepository>();
return services;
}
}Then call it from Program.cs:
builder.Services.AddInfrastructure(
builder.Configuration);ApplicationDbContext, repositories, and Unit of Work should share a compatible scoped lifetime. A singleton service must not capture a scoped DbContext through constructor injection. Creating a context manually with new also bypasses the dependency-injection scope and makes testing and lifetime management harder.
6. Defining Transaction Boundaries
Multiple inserts or updates executed by one SaveChangesAsync call are generally wrapped in a transaction by EF Core when the database provider supports it. This gives simple use cases atomic behavior without requiring an explicit transaction.
For example, an order and its order items can be persisted as one entity graph. The graph is prepared, and one save operation commits it. If saving fails, the changes are not committed as a partial result.
An explicit transaction can be appropriate when a use case requires multiple save operations, several repository operations with intermediate steps, or additional database commands inside the same boundary:
await using var transaction =
await _context.Database.BeginTransactionAsync(cancellationToken);
try
{
await _orders.AddAsync(order, cancellationToken);
await _unitOfWork.SaveChangesAsync(cancellationToken);
await _auditRepository.AddAsync(audit, cancellationToken);
await _unitOfWork.SaveChangesAsync(cancellationToken);
await transaction.CommitAsync(cancellationToken);
}
catch
{
await transaction.RollbackAsync(cancellationToken);
throw;
}Use this pattern only when the use case genuinely needs it. Starting a transaction inside every repository method creates unnecessary complexity and hides the actual transaction boundary.
Common Mistakes
- Calling SaveChanges inside every repository: This prevents a use case from committing changes from multiple repositories as one operation.
- Creating a generic repository for every entity: Abstractions that only repeat basic CRUD operations may add little value. Prefer meaningful methods that express the application's needs.
- Using Include everywhere: Loading unnecessary relationships can produce large result sets and complicated SQL.
- Tracking every read query: Use
AsNoTrackingwhen returned data is read-only and will not be modified. - Registering DbContext as a singleton: DbContext is not thread-safe, and long-lived contexts can cause stale data and memory problems.
- Ignoring CancellationToken: Database work may continue unnecessarily after a client disconnects.
- Referencing Infrastructure from Application: Application code should not expose
DbSet,Include, SQL Server types, or EF Core implementation details.
Practice Exercise
Create a CustomerRepository in the project and complete these steps:
- Define an
ICustomerRepositorycontract in the Application layer. - Add
GetByEmailAsync,GetByIdAsync, andAddAsyncmethods. - Implement the contract in Infrastructure using
ApplicationDbContext. - Choose appropriate tracking behavior for the email lookup.
- Register the repository with dependency injection.
- Use the repository and
IUnitOfWorkin a create-customer use case. - Write an integration test that verifies the customer can be read after it is saved.
Conclusion
In this lesson, we implemented Application-layer repository contracts with EF Core in the Infrastructure layer. Query, create, update, and delete operations stayed inside repository implementations, while persistence timing was coordinated through the Unit of Work.
The most important design decision is that repositories should not independently control the complete transaction or call save operations after every method. The use case defines the boundary, and the DbContext acts as a natural Unit of Work inside that boundary. In the next lessons, we will connect this persistence model to application services, validation, and API endpoints to create a complete end-to-end flow.