Can I configure an interceptor in EntityFramework Core?

后端 未结 3 1293
时光说笑
时光说笑 2020-12-03 01:34

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 b

3条回答
  •  失恋的感觉
    2020-12-03 02:19

    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>
    {
        public void OnCompleted()
        {
        }
    
        public void OnError(Exception error)
        {
        }
    
        public void OnNext(KeyValuePair 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
    {
        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());
    

提交回复
热议问题