How to hook IDbCommandInterceptor only to a specific type of DbContext?

徘徊边缘 提交于 2019-12-06 09:37:30

问题


Currently I'm adding my implementation of IDbCommandInterceptor to the static DbInterception class via a DbConfiguration:

public class LogDbConfiguration : DbConfiguration
{
    public LogDbConfiguration()
    {
        if (AppConfig.LogDebugLevel > LogDebugLevel.Nothing)
        {
            DbInterception.Add(new PerformanceLogDbCommandInterceptor());
        }
    }
}

And this configuration is added to the context that I'd like to hook, as an attribute:

[DbConfigurationType(typeof(LogDbConfiguration))]
public partial class MyEntityFrameworkDb // : DbContext
{
    ...
}

But this hooks the IDbCommandInterceptor to all DbContexts, so I have to check which context I'm coming from all the time:

public class PerformanceLogDbCommandInterceptor : IDbCommandInterceptor
{
    ...
    public void NonQueryExecuted(DbCommand command,
            DbCommandInterceptionContext<int> interceptionContext)
    {
        LogIfMyEntityFrameworkDbContext(command, interceptionContext);
    }
    ...
    private void LogIfMyEntityFrameworkDbContext<T>(DbCommand command,
            DbCommandInterceptionContext<T> interceptionContext)
    {
        ...
        //Log only to MyEntityFrameworkDb 
        if (!(interceptionContext.DbContexts.SingleOrDefault() is MyEntityFrameworkDb))
        {
            return;
        }
        ...
    }
}

I would prefer if I didn't have to do such checks, and only add the interceptor-implementation as observer on a specific context. I haven't been able to figure out a way to do that though. MSDN's article on this says the following:

Interceptors can also be registered at the app-domain level using the DbConfiguration code-based configuration mechanism.

I'm not sure what the "app-domain level" is, but I'm assuming that means the same scope/context as I'm currently doing it in.

Is there a way to do this that is true to the Observer pattern - that is, hooking the interceptor as a listener to the specific type of DbContext?

来源:https://stackoverflow.com/questions/40382013/how-to-hook-idbcommandinterceptor-only-to-a-specific-type-of-dbcontext

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!