Covers EF Core interceptors: IDbCommandInterceptor, ISaveChangesInterceptor, IDbConnectionInterceptor, IMaterializationInterceptor and IQueryExpressionInterceptor; registration with AddInterceptors and DI; lifetime with pooling; suppression results; real uses (audit columns, soft delete, slow-query logging, query hints, Entra ID tokens) and the fact that ExecuteUpdate/ExecuteDelete bypass SaveChanges interceptors.
Interceptors let you run code before and after EF Core operations without touching every call site. The main ones are DbCommandInterceptor (see or change the SQL, time it, or suppress execution and return a cached result), SaveChangesInterceptor (inspect the ChangeTracker in SavingChangesAsync to set audit columns, turn deletes into soft deletes or write outbox rows), and DbConnectionInterceptor (run code as a connection opens, such as setting SESSION_CONTEXT for row-level security). You register them with AddInterceptors, usually resolved from DI. With AddDbContextPool they behave like singletons, so they must not capture scoped services. They don't see everything: ExecuteUpdate/ExecuteDelete bypass SaveChanges interceptors. The trade-off is central, invisible behaviour versus surprise for anyone reading a handler, so keep them few, fast and documented.
"An interceptor is EF Core's extension point around its own operations. Each interface has 'ing' and 'ed' methods:
ReaderExecutingbefore the command goes to SQL Server,ReaderExecutedafter,SavingChangesAsyncbeforeSaveChangessends anything,SavedChangesAsyncafter, plus failure hooks. In the 'ing' methods I can change things or suppress the operation by returning anInterceptionResultwith a result, so EF never hits the database.The three I actually use in production are these. A
SaveChangesInterceptorthat walksChangeTracker.Entries<IAuditable>()and setsCreatedAt,ModifiedByand so on fromTimeProviderand the current user, and turnsDeletedentries of soft-deletable entities intoModifiedwithIsDeleted = true. ADbCommandInterceptorthat logs any command slower than a threshold with its tag, or appendsOPTION (RECOMPILE)to commands tagged for it withTagWith. And aDbConnectionInterceptorthat setsSESSION_CONTEXTwith the tenant id for row-level security. People used to use a connection interceptor to fetch an Entra ID token and setSqlConnection.AccessToken; todayAuthentication=Active Directory Defaultin Microsoft.Data.SqlClient does that for you, so I'd only write one if I needed custom token logic.Registration is
AddInterceptorsin the options. The trap is lifetime: withAddDbContextPool, options are built once, so the interceptor instance is shared by every context and every request. If it captured a scopedICurrentUser, every request would see the first user. I injectIHttpContextAccessoror resolve per call instead. The other trap is coverage:ExecuteUpdateAsyncandExecuteDeleteAsyncdon't go throughSaveChanges, so my audit and soft-delete interceptor silently does nothing for them. The mistake I see is putting business rules in interceptors. They're for cross-cutting plumbing; if a rule matters to the domain, it belongs where people can read it."
| Interface (base class) | Hooks | Typical use |
|---|---|---|
IDbCommandInterceptor (DbCommandInterceptor) |
CommandCreated, ReaderExecuting/Executed, NonQuery..., Scalar..., CommandFailed |
Slow-query logging, hints, caching, command timeouts |
ISaveChangesInterceptor (SaveChangesInterceptor) |
SavingChanges, SavedChanges, SaveChangesFailed |
Audit columns, soft delete, outbox, domain events |
IDbConnectionInterceptor (DbConnectionInterceptor) |
ConnectionOpening/Opened, ConnectionClosing |
SESSION_CONTEXT, custom tokens |
IDbTransactionInterceptor |
TransactionStarting, Committed, RolledBack |
Diagnostics |
IMaterializationInterceptor (EF 7+) |
CreatingInstance, InitializedInstance |
Injecting services into entities, setting non-mapped state |
IQueryExpressionInterceptor (EF 7+) |
QueryCompilationStarting |
Rewriting LINQ expression trees (e.g. default ordering) |
| Operation | Command interceptor | SaveChanges interceptor |
|---|---|---|
| LINQ query | Yes | No |
SaveChanges |
Yes | Yes |
ExecuteUpdate / ExecuteDelete |
Yes | No |
ExecuteSql / FromSql |
Yes | No |
| Migrations | Yes | No |
A 200 ms slow-command interceptor that logged the TagWith tag and duration to Application Insights found [3] queries responsible for [70%] of database time within a day; it added under [5 ยตs] per command because it only allocated when over the threshold.
Checks practical knowledge of EF Core's extension points, including the lifetime and coverage traps that cause real bugs.
Green flags
ExecuteUpdate/ExecuteDelete bypass SaveChanges interceptors.LogTo, query filters) where they exist.Red flags
DbContext.SaveChangesAsync()
-> ISaveChangesInterceptor.SavingChangesAsync (ChangeTracker available)
-> DetectChanges, build commands
-> IDbConnectionInterceptor.ConnectionOpeningAsync (if closed)
-> IDbTransactionInterceptor.TransactionStartingAsync
-> IDbCommandInterceptor.ReaderExecutingAsync (DbCommand: text, parameters)
-> SQL Server
<- IDbCommandInterceptor.ReaderExecutedAsync (duration, DbDataReader)
<- ISaveChangesInterceptor.SavedChangesAsync (rows affected)
Queries skip the SaveChanges layer and go: query compilation (IQueryExpressionInterceptor) -> command -> materialisation (IMaterializationInterceptor).
The 'ing' methods receive and return an InterceptionResult<T>. Return InterceptionResult<DbDataReader>.SuppressWithResult(reader) to skip the database (a cache), or modify command.CommandText in place (hints). For SaveChanges, InterceptionResult<int>.SuppressWithResult(n) skips the save.
EF Core calls the sync hook for SaveChanges() and the async one for SaveChangesAsync(). The base classes have no-op defaults, so override both or share a helper; otherwise synchronous paths (tests, some libraries) silently skip your logic.
AddDbContext: options built per scope (DbContextOptions is scoped by default)
-> (sp, o) => o.AddInterceptors(sp.GetRequiredService<X>()) per scope
AddDbContextPool: options built once, contexts reused
-> interceptor instance shared for the app's lifetime
So with pooling, an interceptor must be thread-safe and stateless, and should get per-request data through an accessor (IHttpContextAccessor, AsyncLocal) at call time. Interceptors are also part of the options, so they change the internal service provider cache key: creating new interceptor instances per context without pooling is fine, but building a new options object per context with different interceptor types creates many internal service providers (EF Core warns about this, warning 10407 'ManyServiceProvidersCreatedWarning').
| Need | Built-in alternative |
|---|---|
| Log SQL | LogTo, ILoggerFactory, TagWith |
| Entra ID auth | Authentication=Active Directory Default / Managed Identity in the connection string |
| Hide deleted rows | Global query filters |
| React to state changes | ChangeTracker.StateChanged / Tracked events |
| Diagnostics without code | DiagnosticListener / OpenTelemetry instrumentation |
Command interceptors run on every command, so keep them allocation-free on the fast path (check a threshold or a tag with StartsWith, don't format strings). SaveChanges interceptors iterating ChangeTracker.Entries() are O(tracked entities); filter with Entries<IAuditable>() and only look at Added/Modified/Deleted.
DbCommandInterceptor that logs commands over 100 ms; run a slow WAITFOR DELAY query to trigger it.SaveChangesInterceptor; then call ExecuteUpdateAsync and confirm the audit column isn't set.AddDbContextPool, call two requests with different users, and observe the leak.SuppressWithResult to return a cached reader for a tagged query.DbConnectionInterceptor that runs EXEC sp_set_session_context 'TenantId', @t and check SESSION_CONTEXT(N'TenantId') in a query.An audit and soft-delete interceptor, and a slow-command interceptor, both pool-safe.
namespace Shop.Data.Interceptors;
using System.Data.Common;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.Extensions.Logging;
public interface IAuditable { DateTimeOffset CreatedAt { get; set; } string? CreatedBy { get; set; } DateTimeOffset? ModifiedAt { get; set; } string? ModifiedBy { get; set; } }
public interface ISoftDeletable { bool IsDeleted { get; set; } DateTimeOffset? DeletedAt { get; set; } }
public interface ICurrentUser { string? Id { get; } }
// Stateless: reads the user at call time through an accessor-backed ICurrentUser registered as singleton.
public sealed class AuditInterceptor(TimeProvider clock, ICurrentUser user) : SaveChangesInterceptor
{
public override InterceptionResult<int> SavingChanges(DbContextEventData e, InterceptionResult<int> result)
{
Apply(e.Context);
return result;
}
public override ValueTask<InterceptionResult<int>> SavingChangesAsync(
DbContextEventData e, InterceptionResult<int> result, CancellationToken ct = default)
{
Apply(e.Context); // override both: sync SaveChanges would otherwise skip auditing
return ValueTask.FromResult(result);
}
private void Apply(DbContext? db)
{
if (db is null) return;
var now = clock.GetUtcNow();
foreach (var entry in db.ChangeTracker.Entries<ISoftDeletable>().Where(x => x.State == EntityState.Deleted))
{
entry.State = EntityState.Modified; // DELETE becomes UPDATE
entry.Entity.IsDeleted = true;
entry.Entity.DeletedAt = now;
}
foreach (var entry in db.ChangeTracker.Entries<IAuditable>())
{
if (entry.State == EntityState.Added) { entry.Entity.CreatedAt = now; entry.Entity.CreatedBy = user.Id; }
else if (entry.State == EntityState.Modified) { entry.Entity.ModifiedAt = now; entry.Entity.ModifiedBy = user.Id; }
}
}
}
public sealed class SlowCommandInterceptor(ILogger<SlowCommandInterceptor> logger) : DbCommandInterceptor
{
private static readonly TimeSpan Threshold = TimeSpan.FromMilliseconds(200);
public override ValueTask<DbDataReader> ReaderExecutedAsync(
DbCommand command, CommandExecutedEventData e, DbDataReader result, CancellationToken ct = default)
{
if (e.Duration > Threshold) // allocate only on the slow path
logger.LogWarning("Slow EF command {DurationMs} ms: {CommandText}", e.Duration.TotalMilliseconds, command.CommandText);
return ValueTask.FromResult(result);
}
}
// Program.cs
builder.Services.AddSingleton(TimeProvider.System);
builder.Services.AddHttpContextAccessor();
builder.Services.AddSingleton<ICurrentUser, HttpContextCurrentUser>(); // reads HttpContext per call
builder.Services.AddSingleton<AuditInterceptor>();
builder.Services.AddSingleton<SlowCommandInterceptor>();
builder.Services.AddDbContextPool<ShopDbContext>((sp, o) => o
.UseSqlServer(builder.Configuration.GetConnectionString("Shop"))
.AddInterceptors(sp.GetRequiredService<AuditInterceptor>(), sp.GetRequiredService<SlowCommandInterceptor>()));
AddDbContextPool. Why it is wrong: the interceptor is effectively a singleton, so every request sees the first request's user or tenant. ValidateScopes doesn't catch it, because the interceptor is resolved inside the options factory rather than injected into a singleton. Instead: give the interceptor only singleton dependencies and read per-request state at call time through an accessor; prove it with an integration test that sends two requests as different users through the pooled context and asserts each row's ModifiedBy.SavingChangesAsync. Why it is wrong: synchronous SaveChanges calls skip your logic. Instead: override both and share a helper.ExecuteUpdate/ExecuteDelete. Why it is wrong: those update or delete rows directly in the database without loading entities, so they never call SaveChanges and rows are hard-deleted or unaudited. Instead: set the columns in the ExecuteUpdate call, or ban ExecuteDelete on soft-deletable sets.Authentication=Active Directory Default (or Managed Identity) in the connection string.I keep a short list of approved interceptors in a service: audit and soft delete, slow-command logging, and occasionally session context for row-level security. Each is documented in an ADR, has its own tests (including the sync path and the pooled-lifetime case), and comes with a known list of what it doesn't cover, with ExecuteUpdate top of that list. I check built-ins first, because every interceptor is something a new team member won't see when they read a handler.
I measure their cost with a BenchmarkDotNet run of a simple query with and without the interceptor, and watch EF Core's event counters (dotnet-counters monitor Microsoft.EntityFrameworkCore) for changes in queries per second after adding one.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| SaveChanges interceptor | Cross-cutting rules on tracked changes | O(tracked entries) per save | Bulk ExecuteUpdate paths |
| Command interceptor | SQL-level logging, hints, caching | Runs on every command | Anything LogTo/TagWith already does |
| Connection interceptor | SESSION_CONTEXT, custom auth |
Per connection open | Standard Entra ID auth |
Override SaveChangesAsync in the context |
One context, simple audit | Couples to the context | Shared across contexts |
Use a SaveChangesInterceptor (registered with AddInterceptors) that, in SavingChanges/SavingChangesAsync, walks ChangeTracker.Entries<IAuditable>() (or every entry that has the columns) and sets CreatedAt/CreatedBy for Added entries and ModifiedAt/ModifiedBy for Modified ones. Get the time from an injected TimeProvider so tests can fake it, and the user from a scoped ICurrentUser service that reads HttpContext.User (or the message's identity in a background worker). If you don't want audit fields on the domain classes, map them as shadow properties (builder.Property<DateTimeOffset>("CreatedAt")) and set them with entry.Property("CreatedAt").CurrentValue. Mark CreatedAt as not modified on updates so it can't be overwritten. Note that ExecuteUpdate and raw SQL bypass the interceptor; use temporal tables when you need full history, not just the last change.
Use Microsoft Entra ID authentication with a managed identity. Steps: 1. set a Microsoft Entra admin on the Azure SQL logical server (optionally enable Microsoft Entra-only authentication to turn off SQL logins); 2. turn on a system- or user-assigned managed identity on the App Service, Container App or AKS workload; 3. connected as the Entra admin, create a contained user for it in the database, CREATE USER [my-api] FROM EXTERNAL PROVIDER;, and grant least privilege (db_datareader, db_datawriter, no DDL for the app); 4. use a connection string with Authentication=Active Directory Default (or Active Directory Managed Identity plus User Id=<client id> for a user-assigned identity). Microsoft.Data.SqlClient gets and refreshes tokens itself, so EF Core needs no code change, and locally the same string uses your Azure CLI or Visual Studio sign-in. No secret exists to leak or rotate.
Every tracked entity costs an entry, an identity-map slot and an original-values snapshot, and DetectChanges scans all of them on every SaveChanges (and on Entries()/Entry()). On one long-lived context the tracked set keeps growing, so each save gets slower and the total becomes roughly quadratic, while memory climbs until the job runs out.
The fixes:
ChangeTracker.Clear() or use a new context per chunk.AsNoTracking() or projections.AutoDetectChangesEnabled around bulk Add loops and call DetectChanges once.ExecuteUpdate/ExecuteDelete, or SqlBulkCopy for millions of inserts.The trade-off: chunking gives up all-or-nothing atomicity, and bypassing the tracker skips interceptors and domain logic.
How to tell it (STAR)
**S:** At [company], after we enabled DbContext pooling on our [claims] API, an audit check found that every edit for [two days] was attributed to [the same user]. **T:** I had to fix it fast because the audit trail was a compliance requirement. **A:** I traced it to our audit interceptor, which captured a scoped current-user service in its constructor. With pooling, EF Core builds the options once, so the interceptor lived for the whole app and kept the first user. I rolled pooling back, made the interceptor stateless with a singleton user accessor that reads the HTTP context per call, back-filled [N thousand] rows from request logs, and added a two-user integration test. **R:** Pooling went back on [a week later], allocations per request dropped by [~15%], and the audit trail has been correct since.
Last updated 23 Nov 2026.