Can I configure an interceptor in EntityFramework Core?

15,319

Solution 1

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.

Solution 2

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

Solution 3

It is coming for EntityFramework Core 3.0: https://github.com/aspnet/EntityFrameworkCore/issues/15066

It will work the same way as the one in EF 6

Share:
15,319

Related videos on Youtube

Warren  P
Author by

Warren P

Software Developer: Web, Desktop, and Server service developer JavaScript (ExtJS/SenchaTouch/jquery), HTML5, CSS C#/ASP.NET MVC/ASP.NET Core/Roslyn/Visual Studio 2015 Delphi/ObjectPascal C (Linux and others) and Objective-C (have an app in the app store) Python C++ Smalltalk/Pharo/Squeak Embedded Systems, and cross-platform stuff (Windows, Linux, Mac OS X) नमस्ते. मैं हिंदी फिल्मों से प्यार है. Bits of code at Bitbucket hosting: https://bitbucket.org/wpostma More bits of code at Github: https://github.com/wpostma

Updated on June 15, 2022

Comments

  • Warren  P
    Warren P over 1 year

    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)

  • Warren  P
    Warren P over 7 years
    The Dependency Injection of a Service sounds like the most promising approach.
  • jhr
    jhr over 6 years
    As of EF Core 1.1, DbContextOptionsBuilder has a method ReplaceService<Told, Tnew>(); that can be used to replace an EF or db Provider(SQL, Mysql, etc) service. ex: options.ReplaceService<DbProviderCompositeMethodCallTranslat‌​or, MyCustomCompositeMethodCallTranslator>(); ... where MyCustom class inherits from the DbProvider class and overrides the appropriate method. But I'm still looking for the internal service that will act like "interceptors".
  • hbulens
    hbulens over 6 years
    @jhr Interceptors are on the roadmap for 2.0 (which the team is working on right now): github.com/aspnet/EntityFramework/wiki/Roadmap
  • Warren  P
    Warren P over 4 years
    What version is this for? You may want to say so, since I doubt it's for 1.0 RC? I wonder if my question even makes sense any more since it's for a pre-release version. BUt your answer is useful so I may edit my question to make it more general to .net core. EF Core 2.0 is supposed to have interceptors.
  • Warren  P
    Warren P over 4 years
    In 2019, it looks like we're somewhere in the EFCOre 2.2 era, and this interceptor feature now exists again.
  • Yepeekai
    Yepeekai over 4 years
    I put the current version information in my answer, I don't know at which version exactly this feature was added. DbInterceptor do not exist directly the way they did in EF6, you have to use DiagnosticListener
  • Mark G
    Mark G over 4 years
    Yep, looks like it made it into EF Core 3.0 Preview 7.

Related