问题
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