English
Unit of Work and transactions
Step 1. The interface
Why. Repositories collect changes; the Unit of Work commits them. Within one request all repositories share the same ChatexDbContext (dependency injection creates one per scope, see Files and registration), so one SaveChangesAsync writes everything the operation changed, in one database transaction. Sending a message adds the message, links its attachments and moves the chat's activity time — all or nothing.
Some operations need more than one save inside one transaction. Registration (topic 8) creates the user through Identity's UserManager, which saves by itself, and then the profile; if the profile fails, the user must disappear too. For such cases the Unit of Work runs a piece of code inside an explicit transaction.
Do.
cs
namespace Chatex.Data.Abstractions;
/// <summary>Commits the changes collected by the repositories of the current scope.</summary>
public interface IUnitOfWork
{
Task<int> SaveChangesAsync(CancellationToken cancellationToken = default);
/// <summary>
/// Runs <paramref name="action"/> in a database transaction and commits it if the action returns normally.
/// If it throws, the transaction is rolled back and pending changes are discarded.
/// Identity's UserManager shares the same DbContext, so its writes join the transaction too.
/// </summary>
Task<T> ExecuteInTransactionAsync<T>(Func<CancellationToken, Task<T>> action, CancellationToken cancellationToken = default);
Task ExecuteInTransactionAsync(Func<CancellationToken, Task> action, CancellationToken cancellationToken = default);
}Func<CancellationToken, Task<T>> is a delegate: an asynchronous function that receives a cancellation token and returns a T. The caller passes a lambda, async ct => { ... }.
Step 2. Unique violations as our own exception
Why. Some rules can only be enforced reliably by the database: one direct chat per pair, unique public handles, unique user names. Two requests at the same moment can both pass a check in C#; the unique index lets only one of them save. The other gets a DbUpdateException from EF Core, with a PostgresException from Npgsql inside, whose SqlState is 23505, "unique violation".
The business layer must handle that case — "this handle is already taken" — but it must not depend on EF Core or Npgsql types. The Unit of Work translates the exception into one of our own.
Do. Create the folder Exceptions:
cs
namespace Chatex.Data.Exceptions;
/// <summary>
/// A save broke a unique index, e.g. a second direct chat for the same pair of users or a taken public handle.
/// Lets callers handle such races without depending on EF Core or Npgsql.
/// </summary>
public sealed class UniqueConstraintException(string? constraintName, Exception innerException)
: Exception($"Unique constraint '{constraintName}' was violated.", innerException)
{
public string? ConstraintName { get; } = constraintName;
}ConstraintName tells which rule was broken, for example ix_chats_public_handle, so a service can return the right error. The original exception is kept as InnerException for the logs.
Step 3. The implementation
Why. SaveChangesAsync is simple; the transaction needs care because of the retries switched on in topic 4 (EnableRetryOnFailure). If a connection drops in the middle of a transaction, EF Core cannot know which commands were applied before the drop. It can only retry safely if it replays the whole transaction. EF Core therefore refuses a hand-made BeginTransaction while retries are on; instead, the transaction must run inside an execution strategy, which repeats the whole block on a transient failure.
Do. Create the folder Repositories:
cs
using Chatex.Data.Abstractions;
using Chatex.Data.Exceptions;
using Microsoft.EntityFrameworkCore;
using Npgsql;
namespace Chatex.Data.Repositories;
internal sealed class UnitOfWork(ChatexDbContext db) : IUnitOfWork
{
public async Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
{
try
{
return await db.SaveChangesAsync(cancellationToken);
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { SqlState: PostgresErrorCodes.UniqueViolation } pg)
{
// The failed entities would be saved again by the next call; drop them.
db.ChangeTracker.Clear();
throw new UniqueConstraintException(pg.ConstraintName, ex);
}
}
public async Task<T> ExecuteInTransactionAsync<T>(
Func<CancellationToken, Task<T>> action, CancellationToken cancellationToken = default)
{
var strategy = db.Database.CreateExecutionStrategy();
return await strategy.ExecuteAsync(async ct =>
{
await using var transaction = await db.Database.BeginTransactionAsync(ct);
try
{
var result = await action(ct);
await transaction.CommitAsync(ct);
return result;
}
catch
{
// Disposing the transaction rolls it back; drop the changes it would have saved.
db.ChangeTracker.Clear();
throw;
}
}, cancellationToken);
}
public Task ExecuteInTransactionAsync(Func<CancellationToken, Task> action, CancellationToken cancellationToken = default) =>
ExecuteInTransactionAsync(async ct =>
{
await action(ct);
return true;
}, cancellationToken);
}Step by step:
- The exception filter
catch (...) when (...)catches only aDbUpdateExceptionwhose inner exception is aPostgresExceptionwith the unique-violation code. The property patternPostgresException { SqlState: PostgresErrorCodes.UniqueViolation } pgchecks the type and the property and names the resultpgin one expression. Every other exception passes through untouched. ChangeTracker.Clear()forgets all tracked entities. Otherwise the failed entity would still be markedAdded, and the nextSaveChangesAsyncof the same request would try to insert it again.CreateExecutionStrategy().ExecuteAsync(...)runs the lambda and, on a transient failure, runs it again from the start. Inside, the transaction is begun, the caller'sactionruns, and the transaction is committed.- On any exception the
await usingdisposes the transaction, which rolls it back, and the tracked changes are cleared. The exception is rethrown withthrow;, which keeps its original stack trace. - The non-generic overload wraps the action in a function that returns
true, so the logic exists only once.
Everything a transaction saves must happen inside the lambda
Because the lambda may run twice, it must create and track its entities itself. An entity created before ExecuteInTransactionAsync and only saved inside would, after a retry, be missing from a context that was cleared. The comment of DependencyInjection.Configure (next chapters) repeats this rule for the readers of the code.
Check
dotnet build succeeds. UnitOfWork is internal and not used by anything yet; it is registered for dependency injection in Files and registration and tested in topic 6.