In this lesson, you will learn how to use EF Core Interceptors to automatically inject data governance and security rules into every database operation across your application.
The Concept: Centralizing Business Rules
When building enterprise applications, you often have global requirements: every "Delete" operation must be a soft delete, or every query must filter out records based on the current user's "TenantID." Rather than duplicating this logic in every service method, you can use Interceptors.
Interceptors act as "middleware" for your database context. By hooking into the pipeline—such as SavingChanges or CommandExecuting—you can inspect or modify database commands globally, ensuring security policies are never accidentally bypassed.
Implementing a Security Interceptor
To enforce a data governance rule, such as ensuring all queries are restricted to a specific region, you can implement IDbCommandInterceptor. Here is a simplified approach to intercepting a command and modifying the SQL before it hits the database:
public class RegionFilteringInterceptor : DbCommandInterceptor
{
public override InterceptionResult<DbDataReader> ReaderExecuting(
DbCommand command,
CommandEventData eventData,
InterceptionResult<DbDataReader> result)
{
// Globally inject a filter into the SQL text
if (command.CommandText.Contains("FROM [Orders]"))
{
command.CommandText = command.CommandText.Replace(
"FROM [Orders]",
"FROM [Orders] WHERE [RegionId] = 'EU'");
}
return base.ReaderExecuting(command, eventData, result);
}
}
Registration
Once your interceptor class is defined, you register it when configuring your DbContext via Dependency Injection:
optionsBuilder.AddInterceptors(new RegionFilteringInterceptor());
Why use this over Global Query Filters?
While "Optimizing Global Filters" (lesson 13) is great for simple expressions, custom interceptors provide granular control over the raw DbCommand. This is vital for complex scenarios, such as auditing sensitive data access, logging slow queries, or modifying SQL strings for legacy database compatibility. By decoupling security logic from your business logic, you ensure that your governance rules remain robust regardless of how many developers work on the application.
Key Takeaway: Interceptors allow you to centralize security and governance rules, ensuring they are applied consistently across every database interaction without cluttering your business logic.