Dekim
Dekim

Reputation: 217

Hangfire and ASP.NET MVC

I'm currently using Hangfire in an ASP.NET MVC 5 project, which uses Ninject to use the same Context in RequestScope.

In Hangfire dashboard, I get random errors like:

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.

How can I make Entity, ASP.NET and Hangfire work without getting all those transaction errors?

I bet those errors can happen on the other side (in web).

Upvotes: 2

Views: 1104

Answers (1)

Kristian Johannessen
Kristian Johannessen

Reputation: 158

We also encountered some issues like this with Hangfire along side Ninject. So we actually create a separate kernel for Hangfire, where everything is bound in thread scope. Something like this:

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;
        }
    }
}

And then in Startup:

GlobalConfiguration.Configuration.UseNinjectActivator(NinjectHangfire.CreateKernelForHangfire());

Upvotes: 2

Related Questions