目前我正在添加我的实现IDbCommandInterceptor https://msdn.microsoft.com/en-us/library/system.data.entity.infrastructure.interception.idbcommandinterceptor(v=vs.113).aspx到静态的DbInterception
类通过DbConfiguration
:
public class LogDbConfiguration : DbConfiguration
{
public LogDbConfiguration()
{
if (AppConfig.LogDebugLevel > LogDebugLevel.Nothing)
{
DbInterception.Add(new PerformanceLogDbCommandInterceptor());
}
}
}
此配置作为属性添加到我想要挂钩的上下文中:
[DbConfigurationType(typeof(LogDbConfiguration))]
public partial class MyEntityFrameworkDb // : DbContext
{
...
}
但这钩住了IDbCommandInterceptor
到所有 DbContext,所以我必须始终检查我来自哪个上下文:
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;
}
...
}
}
如果我不必进行此类检查,而只需将拦截器实现添加为特定上下文中的观察者,我会更愿意。但我还没有找到办法做到这一点。MSDN 对此有文章 https://msdn.microsoft.com/en-us/library/dn469464(v=vs.113).aspx说如下:
拦截器还可以使用 DbConfiguration 基于代码的配置机制在应用程序域级别注册。
我不确定“应用程序域级别”是什么,但我假设这意味着与我当前正在执行的范围/上下文相同。
有没有一种方法可以做到这一点,这符合观察者模式——也就是说,将拦截器作为特定类型的 DbContext 的侦听器挂钩?