2

我目前在 ASP.NET MVC 5 项目中使用 Hangfire,该项目使用 Ninject 在 RequestScope 中使用相同的上下文。

在 Hangfire 仪表板中,我收到如下随机错误:

System.Data.Entity.Core.EntityException:在提供程序连接上启动事务时发生错误。有关详细信息,请参阅内部异常。---> System.Data.SqlClient.SqlException: 不允许新事务,因为会话中还有其他线程在运行。

如何使 Entity、ASP.NET 和 Hangfire 工作而不会出现所有这些事务错误?

我敢打赌,这些错误可能发生在另一边(在网络上)。

4

1 回答 1

2

我们在 Ninject 旁边也遇到了一些类似 Hangfire 的问题。所以我们实际上为 Hangfire 创建了一个单独的内核,其中所有内容都绑定在线程范围内。像这样的东西:

public class NinjectHangfire
{
    public static IKernel CreateKernelForHangfire()
    {
        var kernel = new StandardKernel(/*modules*/);
        try
        {
            kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel).InThreadScope();
            kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>().InThreadScope();
            //other bindings
        }
        catch
        {
            kernel.Dispose();
            throw;
        }
    }
}

然后在启动中:

GlobalConfiguration.Configuration.UseNinjectActivator(NinjectHangfire.CreateKernelForHangfire());
于 2015-06-30T07:18:41.853 回答