IDbCommandInterceptor
接口(interface)没有很好的记录。而且我只找到了一些关于它的稀缺教程:
- 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
还有一些 SO 问题:
这些是我发现的关于 Hook 的建议:
1 - 静态 DbInterception
类:
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
类 Hook 到 DbContext,也不知道在 config 方法的 type
部分放什么。 Another example I found似乎建议您编写记录器的 namespace :
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() { }
}
}
但是正确/预期的方法是什么?
最佳答案
我发现我的 DbContext
类只需要具有 DbConfigurationType
属性,以便在运行时附加配置:
[DbConfigurationType(typeof(MyDBConfiguration))]
public partial class MyDbContext // : DbContext
{
public MyDbContext(string nameOrConnectionString) : base(nameOrConnectionString)
{ }
}
public class MyDBConfiguration : DbConfiguration {
public MyDBConfiguration() {
this.AddInterceptor(new MyCommandInterceptor());
}
}
关于c# - 仅将 IDbInterceptor 挂接到 EntityFramework DbContext 一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40302085/