Appearance
IUnitOfWork
IUnitOfWork saves tracked changes and runs an operation inside a database transaction. The generic contract uses EF Core's configured execution strategy; retry behavior depends on the implementation and provider. A retried delegate may run more than once, so keep retryable work free of external side effects.
Methods
| Method | Return | Description |
|---|---|---|
SaveChangesAsync(CancellationToken) | Task<int> | Save tracked changes |
ExecuteInTransactionAsync(Func<CancellationToken, Task>, CancellationToken) | Task | Execute and commit a void operation |
ExecuteInTransactionAsync<TResult>(Func<CancellationToken, Task<TResult>>, CancellationToken) | Task<TResult> | Execute and return a value |
When a transaction is already active on the same context, a nested call joins it. The outer call owns commit and rollback. An operation failure is rethrown; whether rollback completed depends on the provider and on when the failure occurred.
Auth implementation example
AddGrydAuth registers IGrydAuthUnitOfWork as a scoped service. It extends IUnitOfWork and is resolved from the host's normal dependency injection scope:
csharp
using GrydAuth.Domain.Repositories;
public sealed class UpdateHandler(IGrydAuthUnitOfWork unitOfWork, IPolicyRepository repository)
{
public Task<string> HandleAsync(CancellationToken ct) =>
unitOfWork.ExecuteInTransactionAsync(async token =>
{
var value = await repository.UpdatePolicyAsync(token);
await unitOfWork.SaveChangesAsync(token);
return value;
}, ct);
}IPolicyRepository is an application-specific repository in this example; use the repository methods your host defines. The API contract is exercised against PostgreSQL by the maintained Auth unit-of-work integration tests, which cover value and void commits, rollback after SQL changes have been confirmed, and nested calls joining the outer transaction.
This transaction covers database work using that context. It does not make email, HTTP requests, event publication, or other external side effects atomic with the database. Keep such effects outside retryable transaction delegates or use an explicit outbox/delivery design.
The Auth implementation permits a retry only when transaction creation fails before a transaction is returned. Once work starts, a failed save, callback, or commit marks that GrydAuthDbContext unusable for further writes and prevents the execution strategy from replaying the operation on the same tracked state. Use a new context to verify or continue work. A commit error can leave the outcome unknown; do not assume rollback succeeded or repeat a non-idempotent operation blindly.
Nested scope
INestedUnitOfWork.ExecuteNestedAsync runs an operation that can be kept or discarded without ending the transaction of its owner (a dry run, an attempt that may lose a race). The operation returns a NestedOutcome: NestedOutcome.Keep() / Keep(result) or NestedOutcome.Discard() / Discard(result); the default value discards.
csharp
var rows = await nested.ExecuteNestedAsync(async token =>
{
var imported = await importer.RunAsync(token);
return imported.HasErrors ? NestedOutcome.Discard(imported.Rows) : NestedOutcome.Keep(imported.Rows);
}, ct);AddGrydAuditablePersistence<TContext>() registers it, over the same context as IUnitOfWork. For an idempotent route that must be the context of AddGrydIdempotency<TContext>(): over another context the scope runs in root mode and commits by itself, so Keep is not atomic with the record and Discard undoes nothing of the route's context.
- With a transaction open, the scope saves the owner's pending changes, snapshots the change tracker and creates a savepoint (
gryd_nested_plus a Guid). Keep releases it. Discard, or an exception, runsROLLBACK TO SAVEPOINTandRELEASE, detaches what entered after the snapshot and restores values, concurrency tokens, navigations and domain events. Scopes nest. - Without a transaction (root mode), the scope runs in the execution strategy, opens a transaction and commits on keep or rolls back on discard. Changes the owner left pending are written, or rolled back and put back as pending, together with the scope. Entities loaded inside a discarded scope come back detached. The strategy may repeat the operation in this mode, so keep it repeatable and free of external effects.
- Cost. The snapshot is proportional to the number of tracked entities; with many scopes over a large tracker the cost grows quickly. Cap the items of a batch.
- Never call
ChangeTracker.Clear()inside the operation: it breaks the restore. - Do not issue
SAVEPOINTby raw SQL orROLLBACK TOon a savepoint you did not create. The scope mirrors the savepoint stack of the database; both break it. - The undo is never cancelled midway. If the rollback itself fails, an
AggregateExceptioncarries the original error and the failure. - Locks taken inside a discarded scope are released with the savepoint on PostgreSQL; those of a kept scope stay until the owner ends the transaction.
- Aborted transaction. On PostgreSQL a
COMMITafter a failed command becomes a silentROLLBACK. The audit trail treats the transaction as aborted only after a failed savepoint command, until aROLLBACK TOsucceeds; see the effects below for the broader rule.
TransactionBoundBuffer<T> is the building block for work tied to a transaction: Add, MarkSavepoint, RollBackToSavepoint, ReleaseSavepoint and TakeAll. Items added after a mark disappear on a rollback to it and move up one level on release; TakeAll hands over what is left at commit. It knows nothing about EF Core and is not thread-safe: one instance per context.
After-commit effects
IAfterCommitEffects.Register(name, effect) registers an in-process effect (a cache invalidation, a notification of the same process) that runs once, after the database confirmed the commit. Wire it up for the context:
csharp
services.AddGrydAfterCommitEffects<AppDbContext>();
services.AddDbContext<AppDbContext>((provider, options) => options
.UseNpgsql(connectionString)
.UseGrydAfterCommitEffects(provider));- It runs after the commit and before the HTTP response is written, with the connection still held and
CancellationToken.None. - It is discarded on rollback and when a nested scope is discarded. It is also discarded when the transaction was aborted by the database: any server error (
PostgresException) or cancelled command with the transaction open marks it aborted, and aROLLBACK TOthat succeeds recovers it. The discarded queue is logged as a warning (EventId 21). The audit trail is narrower: it only reacts to a failed savepoint command. - A failure is logged and counted (
gryd.after_commit.effect.failures, taggryd.after_commit.effectwith the registered name, meterGryd.Infrastructure.AfterCommit) and never reaches the caller ofCommitAsync. AddGrydAfterCommitEffects<TContext>()serves one context per host: a second call for another context is ignored.- Do not use the same
DbContextin the effect; open another scope. - Do not register an effect inside an effect, or without a transaction: both throw
InvalidOperationException. - The synchronous commit path runs the effects as sync-over-async; prefer
CommitAsync. AddDbContextPoolis not supported: the scoped interceptor would stay bound to the root container.- A failed command of another context that adopted the same transaction through
UseTransactiondoes not mark the owner's effects as aborted.
Idempotent routes
A route marked [Idempotent] already opens the transaction of the registered context. Handlers on it use the unit of work as usual: a nested call joins that transaction and the route owns commit and rollback. See Idempotent act routes. To undo only part of the act and still answer 2xx, use the nested scope.
Reusable audit rule and unit of work
For a host that does not use the Auth module, Gryd.Infrastructure.Persistence ships the same audit and soft-delete rule and an IUnitOfWork over any EF Core context. Nothing is wired on its own.
csharp
services.AddGrydAuditablePersistence<AppDbContext>(); // interceptor + IUnitOfWork, only when absent
services.AddDbContext<AppDbContext>((provider, options) => options
.UseNpgsql(connectionString)
.UseGrydAuditableEntities(provider));AddGrydAuditablePersistence needs an ICurrentUserService registration from the host.
| Piece | Behavior |
|---|---|
AuditableEntityStamper.Apply(tracker, actor, now) | Added: CreatedAt and CreatedBy. Modified: marked as updated; a tracked row the domain soft-deleted in this save without an author gets the actor as DeletedBy. Deleted: becomes a soft delete carrying the actor. |
AuditableSaveChangesInterceptor | Applies the stamper on SaveChanges and SaveChangesAsync with the current user. With no user, CreatedBy, UpdatedBy and DeletedBy stay null; it never throws. |
EfUnitOfWork<TContext> | SaveChangesAsync delegates. ExecuteInTransactionAsync runs in the execution strategy: begin, run, save, commit. With a transaction already open it joins it and leaves the commit to the owner. |
The rule covers entities that inherit BaseEntity or BaseEntity<TKey>. An entity outside those bases is not touched and Deleted stays a physical removal, which is how an append-only entity stays out. Pair it with ApplySoftDeleteFilters so soft-deleted rows are hidden from queries.
The Auth module shares the rule, not the interceptor: GrydAuthDbContext calls the stamper itself, with Guid.Empty when there is no user, and keeps IGrydAuthUnitOfWork for its own semantics.
When DeletedBy stays empty
An author the domain gives is always kept, and a domain soft delete with no real user (null or Guid.Empty) has no author. In these cases the stamper cannot fill it, so the deletion looks like one made by the system:
| Case | Why | What the host does when it needs the author |
|---|---|---|
Detached entity: loaded with AsNoTracking or in another context, soft-deleted, then saved with Update or RepositoryBase.UpdateAsync | There is no original value, so the save cannot be told apart from an edit of a row already deleted | Load the row in the context that saves it, or call entity.Delete(currentUser.UserId) |
ExecuteUpdate, ExecuteDelete or raw SQL | They do not pass through the change tracker, so no stamp runs, including UpdatedBy | Set the columns in the statement, as in the example below. ExecuteDelete on a row is physical |
| Rows deleted before this rule | The stamper never rewrites past rows | See the correction below |
csharp
await context.Notes
.Where(note => note.ExpiresAt < now)
.ExecuteUpdateAsync(set => set
.SetProperty(note => note.IsDeleted, true)
.SetProperty(note => note.DeletedAt, now)
.SetProperty(note => note.DeletedBy, currentUser.UserId)
.SetProperty(note => note.UpdatedAt, now)
.SetProperty(note => note.UpdatedBy, currentUser.UserId), cancellationToken);The correction of past rows is optional and belongs to the host. A row whose delete was the last write and went through the stamper has its author in UpdatedBy, but the columns do not prove it: a later edit, or a delete made before the stamper was on, puts someone else there or nothing. Accept only rows where the two dates match, and review what is left over. Adjust the threshold to how far the two clocks can be apart, and run it once in a migration or script with the host's own table and column names:
sql
UPDATE notes
SET deleted_by = updated_by
WHERE is_deleted
AND deleted_by IS NULL
AND updated_by IS NOT NULL
AND updated_by <> '00000000-0000-0000-0000-000000000000'
AND ABS(EXTRACT(EPOCH FROM (updated_at - deleted_at))) < 1;