Interceptors
Interceptors let you run code at key moments inside EF Core: before SaveChanges, before a command is sent, or when a connection opens. This lesson builds the most common one, automatic audit fields, and shows other good uses.
- StartSaveChangesAsync calledYour code saves
- Step 2SavingChangesAudit interceptor sets dates
- Step 3Command createdCommand interceptor can log or change SQL
- Step 4Command executedTiming available afterwards
- EndSavedChangesPublish events after success
What interceptors are for
An interceptor is a class EF Core calls at a fixed point. It keeps cross-cutting concerns, such as setting CreatedAt, logging slow commands or adding query hints, out of your controllers and in one place.
The main types are ISaveChangesInterceptor, IDbCommandInterceptor, IDbConnectionInterceptor and IDbTransactionInterceptor. Base classes such as SaveChangesInterceptor let you override only what you need.
Audit fields on every save
public interface IAudited
{
DateTime CreatedAt { get; set; }
DateTime? UpdatedAt { get; set; }
}
public class AuditInterceptor(TimeProvider clock) : SaveChangesInterceptor
{
public override ValueTask<InterceptionResult<int>> SavingChangesAsync(
DbContextEventData eventData, InterceptionResult<int> result, CancellationToken ct = default)
{
var now = clock.GetUtcNow().UtcDateTime;
foreach (var e in eventData.Context!.ChangeTracker.Entries<IAudited>())
{
if (e.State == EntityState.Added) e.Entity.CreatedAt = now;
if (e.State == EntityState.Modified) e.Entity.UpdatedAt = now;
}
return base.SavingChangesAsync(eventData, result, ct);
}
}Registering it
Register the interceptor in dependency injection and add it to the context options, so it can use other services.
builder.Services.AddSingleton(TimeProvider.System);
builder.Services.AddSingleton<AuditInterceptor>();
builder.Services.AddDbContext<ShopContext>((sp, o) => o
.UseSqlServer(builder.Configuration.GetConnectionString("Shop"))
.AddInterceptors(sp.GetRequiredService<AuditInterceptor>()));Other good uses
- A DbCommandInterceptor that logs commands slower than 500 ms with their tag.
- Adding OPTION (RECOMPILE) to commands tagged for it.
- A connection interceptor that sets SESSION_CONTEXT for row-level security.
- Publishing domain events after SavedChanges succeeds.
- Keep interceptors fast and free of surprises; hidden behaviour is hard to debug.
Interview question
How would you set CreatedAt and UpdatedAt automatically on every save?
Create a SaveChangesInterceptor that overrides SavingChanges and SavingChangesAsync, walks ChangeTracker.Entries for entities implementing an interface such as IAudited, and sets CreatedAt for Added entries and UpdatedAt for Modified ones. Register it with AddInterceptors. Overriding SaveChanges in the DbContext also works, but an interceptor keeps the context clean and can use injected services.
Want the full details? Read the official Microsoft documentation for this topic.