Hangfire 和 ASP.NET MVC

Hangfire and ASP.NET MVC

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

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

System.Data.Entity.Core.EntityException: An error occurred while starting a transaction on the provider connection. See the inner exception for details. ---> System.Data.SqlClient.SqlException: New transaction is not allowed because there are other threads running in the session.

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

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

我们在使用 Hangfire Ninject 时也遇到了类似的问题。所以我们实际上为 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());