English
Timestamps with an interceptor
Step 1. One place for the clock
Why. In topic 3 the entities got the interfaces IHasCreatedAt and IHasUpdatedAt. Now something must fill them. Writing chat.CreatedAt = DateTimeOffset.UtcNow in every service has two problems:
- someone forgets it, and a chat is created on 1 January of the year 1 (
default(DateTimeOffset)); - tests cannot control the time. A test of "a refresh token expires after 30 days" or "an unsent upload is removed after 24 hours" would have to wait.
EF Core offers interceptors: objects that EF Core calls at certain moments, for example just before it saves. A SaveChangesInterceptor sees every entity the context is about to insert or update and can change it. That is the one place where timestamps are set.
The current time does not come from DateTimeOffset.UtcNow either, but from an injected TimeProvider — an abstract class of .NET 8 and later. The application uses TimeProvider.System, the real clock; tests replace it with FakeTimeProvider, a clock they can move forward by hand (topic 7).
Do. Create the folder Interceptors and the interceptor in it:
cs
using Chatex.Data.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
namespace Chatex.Data.Interceptors;
/// <summary>Fills <see cref="IHasCreatedAt"/> and <see cref="IHasUpdatedAt"/> before every save.</summary>
internal sealed class TimestampInterceptor(TimeProvider timeProvider) : SaveChangesInterceptor
{
public override InterceptionResult<int> SavingChanges(DbContextEventData eventData, InterceptionResult<int> result)
{
Stamp(eventData.Context);
return result;
}
public override ValueTask<InterceptionResult<int>> SavingChangesAsync(
DbContextEventData eventData,
InterceptionResult<int> result,
CancellationToken cancellationToken = default)
{
Stamp(eventData.Context);
return ValueTask.FromResult(result);
}
private void Stamp(DbContext? context)
{
if (context is null)
{
return;
}
var now = timeProvider.GetUtcNow();
foreach (var entry in context.ChangeTracker.Entries())
{
if (entry.State == EntityState.Added && entry.Entity is IHasCreatedAt created && created.CreatedAt == default)
{
created.CreatedAt = now;
if (entry.Entity is Chat chat && chat.LastActivityAt == default)
{
chat.LastActivityAt = now;
}
}
if (entry.State is EntityState.Added or EntityState.Modified && entry.Entity is IHasUpdatedAt updated)
{
updated.UpdatedAt = now;
}
}
}
}How it works:
- Two overrides.
SaveChangesandSaveChangesAsyncare separate entry points of EF Core; overriding only one would skip the timestamps for the other. Both callStampand return theresultunchanged, which tells EF Core to continue saving as usual. ChangeTracker.Entries()lists every entity the context tracks, with its state:Added(will be inserted),Modified(will be updated),Deleted,Unchanged.- Added entities get
CreatedAt— but only if it is stilldefault. A test or a data import may set the creation time on purpose, and the interceptor respects that. A new chat also gets itsLastActivityAt, because an empty chat must still have a place in the chat list. - Added or modified entities get
UpdatedAt. The patternEntityState.Added or EntityState.Modifiedis the sameorcombinator we used inCanPost. - One
nowfor the whole save. All entities saved together get exactly the same time, so a chat and its first members have equal timestamps.
ChatMember implements IHasCreatedAt.CreatedAt explicitly, mapped to JoinedAt (topic 3). The interceptor sees only the interface, so new members get their JoinedAt without the interceptor knowing about that property.
Why not a database default?
PostgreSQL could fill created_at with DEFAULT now(). But then the value is set by the database clock, not by the TimeProvider of the test, and EF Core would have to read it back after each insert. Setting the value in C# keeps one clock for everything.
The interceptor needs a TimeProvider, so it is created by dependency injection and added to the context options when the data layer is registered — that comes with the other services in topic 5. Until then, contexts created by the dotnet ef tool simply do not stamp times, which is fine: the tool only reads the model.
Check
dotnet build succeeds. The interceptor is tested in topic 6: a registered user must have a CreatedAt that is not default.