Learning to Use Interceptors in Entity Framework Core

Welcome everyone to a new post on Entity Framework where today we are going to look at a slightly more advanced topic in Entity Framework: interceptors.

 

 

1 - What are interceptors?

Before jumping into the code, it's very important to understand what interceptors are. Simply put, they are classes that can manipulate queries or commands to a database before or after they are executed.

 

Interceptors use a programming technique that can be described as aspect-oriented programming (AOP), which allows us to intercept specific points of execution in our applications, enabling us to add additional functionality without having to modify existing code.

 

In Entity Framework Core, they allow us to intercept low-level database operations, giving us the ability to extend and customize database behavior.

In this post, we will see a simple example, but in the next post, we will see second-level cache, which is implemented using interceptors.

 

 

2 - Are interceptors triggers?

At first glance, you might think that an interceptor is like a trigger in the database, and well, that's not too far off. And although they are similar in that both can take action before or after certain events, they are not the same. Still, as a comparison point, it helps to understand how they work.

 

To go into a bit more detail, interceptors are much more complete; let me explain: a trigger usually executes when you have CRUD operations in the database itself, while an interceptor also has the ability to act, for example, when a connection is opened or closed, transactions, and more.

 

Obviously, the code in interceptors is written in C#, so the logic is within the application itself. This means that in addition to taking action in the database, you can inject services or run any code from the interceptor.

 

 

3 - Types of Interceptors in Entity Framework Core

In Entity Framework Core, we have a set of default interceptors that will act on different performed actions:

  • DbCommandInterceptor: Allows you to intercept the execution of SQL commands, including select, insert, update, and delete operations. This is by far the most commonly used interceptor, both in companies (if you use any), and in popular GitHub libraries.

  • DbconnectionInterceptor: Allows you to intercept when a connection to the database is opened or closed. In addition to typical logging, one example of its use would be to change the connection string directly at runtime (although there are better ways to do this).

  • DbTransactionInterceptor: Allows you to intercept transaction operations, useful for knowing when a transaction is started, committed, or rolled back.

  • DbParameterInterceptor: Allows you to intercept operations related to SQL command parameters. For example, you can change the value of the parameters.

  • SaveChangesInterceptor: Allows you to intercept save changes operations in the database. Useful if you want to perform additional actions just before or after those changes.

  • DbContextInterceptor: Allows you to intercept events related to the Entity Framework DbContext lifecycle.

In addition to these, there are others. For example, the lazy loading we saw a couple of posts ago is done through an interceptor.

Each of these interceptors provides methods that you can override to customize their behavior.

 

 

4 - Creating an Interceptor for Entity Framework Core

To understand the implementation, what we'll do is simply look at an example of an interceptor. In this case, a very simple one that, when reading from the database, will just display what's happening on the screen.

 

To do this, we create a class that inherits from DbCommandInterceptor. Here you can override multiple methods, the ones used for reading or for commands. In this case, what we have to do is override the ReaderExecuting method, which is the one for reading.

public class ReadExampleInterceptor : DbCommandInterceptor
{
    public override InterceptionResult<DbDataReader> ReaderExecuting(DbCommand command, CommandEventData eventData, InterceptionResult<DbDataReader> result)
    {
      
    }
}

And just to check that it works, we'll add some console output. In this case, we'll include a message before it executes and another after:

public class ReadExampleInterceptor : DbCommandInterceptor
{
    public override InterceptionResult<DbDataReader> ReaderExecuting(DbCommand command, CommandEventData eventData,
        InterceptionResult<DbDataReader> result)
    {
        Console.WriteLine("======== HERE start Executing ==========");
        return base.ReaderExecuting(command, eventData, result);
    }
    
    public override DbDataReader ReaderExecuted(DbCommand command, CommandExecutedEventData eventData, DbDataReader result)
    {
        Console.WriteLine("======== HERE executed ==========");
        return base.ReaderExecuted(command, eventData, result);
    }
}

Make sure not to forget to call the base method so that all the code keeps working as expected.

 

Before testing the code, we need to register this interceptor, and to do so, we do it in the DbContextOptionsBuilder of the DbContext, either in the OnConfiguring method or when adding it to the dependency container:

public static void AddMySql(this IServiceCollection services)
{
    services.AddDbContext<CursoEfContext>(options=>
        options
        .UseLazyLoadingProxies()
        .AddInterceptors(new ReadExampleInterceptor())
        .UseMySQL("server=127.0.0.1;port=4306;database=cursoEF;user=root;password=cursoEFpass"));
}



Now if we run the code, we can see that it works when we make queries with Entity Framework to the database:

example of interceptor execution in entity framework

This post was translated from Spanish. You can see the original one here.
If there is any problem you can add a comment bellow or contact me in the website's contact form

Uso del bloqueador de anuncios adblock

Hola!

Primero de todo bienvenido a la web de NetMentor donde podrás aprender programación en C# y .NET desde un nivel de principiante hasta más avanzado.


Yo entiendo que utilices un bloqueador de anuncios como AdBlock, Ublock o el propio navegador Brave. Pero te tengo que pedir por favor que desactives el bloqueador para esta web.


Intento personalmente no poner mucha publicidad, la justa para pagar el servidor y por supuesto que no sea intrusiva; Si pese a ello piensas que es intrusiva siempre me puedes escribir por privado o por Twitter a @NetMentorTW.


Si ya lo has desactivado, por favor recarga la página.


Un saludo y muchas gracias por tu colaboración

© copyright 2025 NetMentor | Todos los derechos reservados | RSS Feed

Buy me a coffee Invitame a un café