Entity Framework Core Interview Question #166

What is a SaveChangesInterceptor used for?

Advanced Mapping, Interceptors, Value Conversions & Architecture Senior Advanced

Quick Interview Answer

A SaveChangesInterceptor can execute logic before or after SaveChanges and when saving fails. Typical uses include auditing metadata, domain-event coordination, diagnostics, or enforcing persistence-level conventions. Avoid placing core business decisions in an interceptor because hidden side effects can make the application difficult to reason about and test.

Detailed Explanation

A SaveChangesInterceptor can execute logic before or after SaveChanges and when saving fails. Typical uses include auditing metadata, domain-event coordination, diagnostics, or enforcing persistence-level conventions. Avoid placing core business decisions in an interceptor because hidden side effects can make the application difficult to reason about and test.

Code Example

builder.Services.AddDbContext<AppDbContext>(options =>
    options.AddInterceptors(new AuditSaveChangesInterceptor()));