IDbCommandInterceptor
interface documentation is inadequate, and only a few tutorials on it are available, such as:
- http://www.entityframeworktutorial.net/entityframework6/database-command-interception.aspx
- https://msdn.microsoft.com/en-us/data/jj556606%28v=vs.113%29.aspx
- https://entityframework.codeplex.com/wikipage?title=Interception
- https://www.tutorialspoint.com/entity_framework/entity_framework_command_interception.htm
- https://msdn.microsoft.com/en-us/data/dn469464%28v=vs.113%29.aspx
Additionally, a few Stack Overflow questions:
Here are the suggestions for hooking:
1 - The static DbInterception
class:
DbInterception.Add(new MyCommandInterceptor());
2 - 在一个DbConfiguration
类中执行上述建议
public class MyDBConfiguration : DbConfiguration {
public MyDBConfiguration() {
DbInterception.Add(new MyCommandInterceptor());
}
}
3 - 使用配置文件:
<entityFramework>
<interceptors>
<interceptor type="EFInterceptDemo.MyCommandInterceptor, EFInterceptDemo"/>
</interceptors>
</entityFramework>
虽然我无法弄清楚如何将 DbConfiguration
类连接到 DbContext,也不知道在配置方法的 type
部分中要放什么。我找到了另一个示例,似乎建议您编写记录器的名称空间:type="System.Data.Entity.Infrastructure.Interception.DatabaseLogger, EntityFramework"
我注意到 DataBaseLogger
实现了IDisposable
、IDbConfigurationInterceptor
和
IDbInterceptor
。 IDbCommandInterceptor
也实现了IDbInterceptor
,所以我尝试将其格式化为这样(但没有成功):
type="DataLayer.Logging.MyCommandInterceptor, DataLayer"
当我直接调用静态 DbInterception
类时,每次调用它都会添加另一个拦截器。所以我的快速而简单的解决方案是利用静态构造函数:
//This partial class is a seperate file from the Entity Framework auto-generated class,
//to allow dynamic connection strings
public partial class MyDbContext // : DbContext
{
public Guid RequestGUID { get; private set; }
public MyDbContext(string nameOrConnectionString) : base(nameOrConnectionString)
{
DbContextListeningInitializer.EnsureListenersAdded();
RequestGUID = Guid.NewGuid();
//Database.Log = m => System.Diagnostics.Debug.Write(m);
}
private static class DbContextListeningInitializer
{
static DbContextListeningInitializer() //Threadsafe
{
DbInterception.Add(new MyCommandInterceptor());
}
//When this method is called, the static ctor is called the first time only
internal static void EnsureListenersAdded() { }
}
}
但是,正确/预期的方法是什么?
MyDBConfiguration
构造函数中,你不必使用那个静态类,你可以使用this.AddInterceptor()
方法。 - Jan 'splite' K.DbConfiguration
应用于App-Domain级别。它还指出,当您的DbContext
与配置不在同一个程序集中时,应使用DbConfigurationType
属性:https://learn.microsoft.com/en-us/ef/ef6/fundamentals/configuring/code-based - Adolfo Perez