📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

๐Ÿ“š Interview question

What are EF Core interceptors? Explain command, SaveChanges and connection interceptors, how you register them and what lifetime they effectively have, and give real production uses, including what they cannot see.

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.

Mid-Level Theory Intermediate auditing azure-sql diagnostics ef-core interceptors savechanges

๐ŸŽฏ Key points

  • Interceptors hook EF Core operations before and after: commands, SaveChanges, connections, transaction lifecycle events (IDbTransactionInterceptor), materialisation and query compilation (EF Core 7+)
  • DbCommandInterceptor: ReaderExecuting/Executed, command text and duration, can modify or suppress (InterceptionResult.SuppressWithResult)
  • SaveChangesInterceptor: SavingChangesAsync sees the ChangeTracker; used for audit columns, soft delete, outbox
  • DbConnectionInterceptor: ConnectionOpeningAsync, e.g. setting SESSION_CONTEXT for row-level security
  • Registered with optionsBuilder.AddInterceptors; with DbContext pooling they are effectively singletons, so no scoped state captured
  • ExecuteUpdate/ExecuteDelete (EF Core 7+) and raw SQL skip SaveChanges interceptors but still pass through command interceptors
  • Command interceptors run on every command: keep the fast path allocation-free and benchmark the overhead
  • Test the sync path, the pooled two-user case and the ExecuteUpdate gap in integration tests; prefer built-ins first

โฑ 30-second answer

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.

๐Ÿ—ฃ Full answer (senior)

How I would answer this in an interview

"An interceptor is EF Core's extension point around its own operations. Each interface has 'ing' and 'ed' methods: ReaderExecuting before the command goes to SQL Server, ReaderExecuted after, SavingChangesAsync before SaveChanges sends anything, SavedChangesAsync after, plus failure hooks. In the 'ing' methods I can change things or suppress the operation by returning an InterceptionResult with a result, so EF never hits the database.

The three I actually use in production are these. A SaveChangesInterceptor that walks ChangeTracker.Entries<IAuditable>() and sets CreatedAt, ModifiedBy and so on from TimeProvider and the current user, and turns Deleted entries of soft-deletable entities into Modified with IsDeleted = true. A DbCommandInterceptor that logs any command slower than a threshold with its tag, or appends OPTION (RECOMPILE) to commands tagged for it with TagWith. And a DbConnectionInterceptor that sets SESSION_CONTEXT with the tenant id for row-level security. People used to use a connection interceptor to fetch an Entra ID token and set SqlConnection.AccessToken; today Authentication=Active Directory Default in Microsoft.Data.SqlClient does that for you, so I'd only write one if I needed custom token logic.

Registration is AddInterceptors in the options. The trap is lifetime: with AddDbContextPool, options are built once, so the interceptor instance is shared by every context and every request. If it captured a scoped ICurrentUser, every request would see the first user. I inject IHttpContextAccessor or resolve per call instead. The other trap is coverage: ExecuteUpdateAsync and ExecuteDeleteAsync don't go through SaveChanges, 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."


The interceptor types

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)

What they see

Operation Command interceptor SaveChanges interceptor
LINQ query Yes No
SaveChanges Yes Yes
ExecuteUpdate / ExecuteDelete Yes No
ExecuteSql / FromSql Yes No
Migrations Yes No

Production example

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.

๐Ÿ” What the interviewer is checking

Checks practical knowledge of EF Core's extension points, including the lifetime and coverage traps that cause real bugs.

Green flags

  • Names the main interceptor types and a real use for each.
  • Knows ExecuteUpdate/ExecuteDelete bypass SaveChanges interceptors.
  • Raises the singleton-like lifetime with pooling.
  • Prefers built-ins (connection-string auth, LogTo, query filters) where they exist.

Red flags

  • Puts business rules in interceptors.
  • Has never considered sync vs async overrides.
  • Thinks interceptors run for raw ADO.NET calls on the same connection.

๐Ÿ“š Learn in depth

1. Where interceptors sit

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).

2. Suppression and modification

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.

3. Sync and async

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.

4. Registration and lifetime

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').

5. Interceptors vs alternatives

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

6. Costs

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.

Try it yourself

  1. Write a DbCommandInterceptor that logs commands over 100 ms; run a slow WAITFOR DELAY query to trigger it.
  2. Build an audit SaveChangesInterceptor; then call ExecuteUpdateAsync and confirm the audit column isn't set.
  3. Register an interceptor that captures a scoped service under AddDbContextPool, call two requests with different users, and observe the leak.
  4. Use SuppressWithResult to return a cached reader for a tagged query.
  5. Add a DbConnectionInterceptor that runs EXEC sp_set_session_context 'TenantId', @t and check SESSION_CONTEXT(N'TenantId') in a query.

๐Ÿ’ป Code

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>()));

โš  Common mistakes

  • Mistake: Capturing a scoped service (current user, tenant) in an interceptor used with 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.
  • Mistake: Overriding only SavingChangesAsync. Why it is wrong: synchronous SaveChanges calls skip your logic. Instead: override both and share a helper.
  • Mistake: Relying on a SaveChanges interceptor for audit or soft delete while using 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.
  • Mistake: Doing I/O or heavy string formatting in a command interceptor on every command. Why it is wrong: it adds latency and allocations to every query, which is noticeable at thousands of queries per second. Instead: check a cheap condition first and benchmark with and without the interceptor.
  • Mistake: Writing a connection interceptor to get Entra ID tokens by hand. Why it is wrong: it's extra code, caching and refresh logic the driver already provides. Instead: Authentication=Active Directory Default (or Managed Identity) in the connection string.
  • Mistake: Hiding business rules (pricing, validation) in interceptors. Why it is wrong: they're invisible from the handler and hard to test. Instead: keep domain logic in the domain; interceptors for plumbing.
  • Mistake: Creating a new options object with new interceptor types per context. Why it is wrong: EF Core builds a new internal service provider each time, leaking memory and slowing start-up. Instead: register once through DI.

๐Ÿ› Senior insight: trade-offs

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

๐Ÿ”— Follow-ups the interviewer may ask

  1. When: Candidate mentions audit columns in a SaveChanges interceptor. Why: Checks the audit-column use case in detail.
    How to answer

    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.

  2. When: Candidate mentions access tokens or Entra ID in a connection interceptor. Why: Checks passwordless Azure SQL auth versus a hand-written connection interceptor.
    How to answer

    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.

  3. When: Candidate mentions ExecuteUpdate skipping interceptors. Why: Checks when ExecuteUpdate is used and what it bypasses.
    How to answer

    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:

    • Chunk: save every few hundred to few thousand entities, then ChangeTracker.Clear() or use a new context per chunk.
    • Read with AsNoTracking() or projections.
    • Turn off AutoDetectChangesEnabled around bulk Add loops and call DetectChanges once.
    • For set-based changes, skip the tracker with 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.

๐Ÿ›  Real-world problems: how you handle them

Audit columns attributed to the wrong user after enabling DbContext pooling
Situation
A [claims-processing] API on ASP.NET Core and Azure SQL with [~150] staff users; audit columns (`ModifiedBy`) are a compliance requirement. The team switched to `AddDbContextPool` to cut allocations.
Signals
An internal audit query showed [thousands of] edits all attributed to [one user] since the release; no errors in Application Insights; the change log matched the pooling release date.
Investigation
Reviewed the interceptor: its constructor took a scoped `ICurrentUser` and stored the user id in a field. Under `AddDbContextPool`, options (and so the interceptor) were built once from the first scope. Reproduced in an integration test with `WebApplicationFactory`: two requests from different users, both audited as the first.
Resolution
Immediately: rolled back to `AddDbContext`. Then: changed `ICurrentUser` to a singleton reading `IHttpContextAccessor` per call, made the interceptor stateless, re-enabled pooling, and back-filled `ModifiedBy` for the affected window from the API request logs (user id + entity id).
Prevention
An integration test with two users through the pooled context; a code-review rule that interceptors take only singleton dependencies; `ValidateScopes` on in development; an ADR describing interceptor lifetimes under pooling.

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.

โ†ฉ Usually asked after

More in Advanced EF Core

Last updated 23 Nov 2026.

๐ŸŒ Sangam's Webring

โช Previous ๐Ÿ  Main Next โฉ
๐Ÿ’ฌ Chat with me