仅将IDbInterceptor挂接到EntityFramework DbContext一次

时间:2016-10-28 09:28:01

标签: c# entity-framework logging entity-framework-6 interceptor

IDbCommandInterceptor界面没有很好的记录。而且我只发现了一些稀缺的教程:

还有一些问题:

这些是关于挂钩的建议我发现:

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类挂钩到DbContext,但也没有把它放在config方法的type部分。 Another example I found似乎建议您编写记录器的命名空间:

type="System.Data.Entity.Infrastructure.Interception.DatabaseLogger, EntityFramework"

我注意到DataBaseLogger实现了IDisposableIDbConfigurationInterceptor
    IDbInterceptorIDbCommandInterceptor也实现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() { }
    }
}

但是这样做的正确/预期方法是什么?

2 个答案:

答案 0 :(得分:7)

我发现我的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());
    }
}

答案 1 :(得分:3)

docs表示您可以将其放入Application_Start

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
    DbInterception.Add(new SchoolInterceptorTransientErrors());
    DbInterception.Add(new SchoolInterceptorLogging());
}

重要的是它只能被召唤一次。