Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I configure an interceptor in EntityFramework Core?

In the old (pre .net core) era's entity framework 6 as shown in this blog post there is a way to configure an interceptor which can log all slow queries including a stack backtrace.

[ NOTE: In Entity Framework Core prior to version 3.0 this was not possible, thus the original question asked what to do instead. Since the time this question was asked, new options and new versions of EF Core have been released. This question is historical now in nature, and some of the answers that were added later reference other newer versions of EF Core, where interceptors may have been reintroduced, to achieve feature parity with the pre-core era entity framework ]

A question from 2015 about an earlier beta of what was then called EF7, suggests that it was not possible yet in asp.net vnext early betas.

Yet, the whole design of EF Core is to be composable, and in discussions on github bug tracker here that a technique might be possible where you subclass some low level class like SqlServerConnection and then override some method in there, to get some points you could hook before and after a query is executed, and add some low level logging if a millisecond timer value was executed.

(Edit: References to pre-release information from 2015 removed in 2020)

like image 276
Warren P Avatar asked Jun 06 '16 15:06

Warren P


People also ask

What is interceptor in asp net core?

An interceptor is a class that implements IInterceptor interface (of Castle Windsor). It defines the Intercept method which gets an IInvocation argument. With this invocation argument, we can investigate the executing method, method arguments, return value, method's declared class, assembly and much more.

Should I use EF6 or EF core?

Keep using EF6 if the data access code is stable and not likely to evolve or need new features. Port to EF Core if the data access code is evolving or if the app needs new features only available in EF Core. Porting to EF Core is also often done for performance.

Can you use EF6 with .NET core?

You can't put an EF6 context in an ASP.NET Core project because . NET Core projects don't support all of the functionality that EF6 commands such as Enable-Migrations require.

What types of database interaction does the EF6 interceptor class allow you to intercept?

Entity Framework Core (EF Core) interceptors enable interception, modification, and/or suppression of EF Core operations. This includes low-level database operations such as executing a command, as well as higher-level operations, such as calls to SaveChanges.


2 Answers

Update: Interception of database operations is now available in EF Core 3.0.

Original answer:


EF Core does not have "interceptors" or similar lifecycle hooks yet. This feature is tracked here: https://github.com/aspnet/EntityFramework/issues/626.

Overriding a low-level component may be unnecessary if all you want is log output. Many low-level EF Core components already produce logging, logging including query execution. You can configure EF to use a custom logger factory by calling DbContextOptionsBuilder.UseLoggerFactory(ILoggerFactory factory). (See https://docs.asp.net/en/latest/fundamentals/logging.html and https://github.com/aspnet/Logging for more details on this logger interface.) EF Core produces some notable log events with well-define event IDs. (See Microsoft.EntityFrameworkCore.Infrastructure.CoreLoggingEventId in 1.0.0-rc2, which was renamed to justMicrosoft.EntityFrameworkCore.Infrastructure.CoreEventId for 1.0.0 RTM.) See https://docs.efproject.net/en/latest/miscellaneous/logging.html for examples of doing this.

If you need additional logging beyond what EF Core components already produce, you will need to override EF Core's lower-level components. This is best done by overriding the existing component and added this overridding version to EF via dependency injection. Doing this requires configuring a custom service provider for EF to use internally. This is configured by DbContextOptionsBuilder.UseInternalServiceProvider(IServiceProvider services) See https://docs.efproject.net/en/latest/miscellaneous/internals/services.html for more details on how EF uses services internally.

like image 122
natemcmaster Avatar answered Oct 14 '22 20:10

natemcmaster


Here is an example found on github from ajcvickers on how to use an Interceptor in EF CORE (2.2 at the time of answering this question):

public class NoLockInterceptor : IObserver<KeyValuePair<string, object>>
{
    public void OnCompleted()
    {
    }

    public void OnError(Exception error)
    {
    }

    public void OnNext(KeyValuePair<string, object> value)
    {
        if (value.Key == RelationalEventId.CommandExecuting.Name)
        {
            var command = ((CommandEventData)value.Value).Command;

            // Do command.CommandText manipulation here
        }
    }
}

Next, create a global listener for EF diagnostics. Something like:

public class EfGlobalListener : IObserver<DiagnosticListener>
{
    private readonly NoLockInterceptor _noLockInterceptor = new NoLockInterceptor();

    public void OnCompleted()
    {
    }

    public void OnError(Exception error)
    {
    }

    public void OnNext(DiagnosticListener listener)
    {
        if (listener.Name == DbLoggerCategory.Name)
        {
            listener.Subscribe(_noLockInterceptor);
        }
    }
}

And register this as part of application startup:

DiagnosticListener.AllListeners.Subscribe(new EfGlobalListener());
like image 32
Yepeekai Avatar answered Oct 14 '22 20:10

Yepeekai