Transaction and ASP.NET MVC5

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

I defined a custom Kernel for Hangfire, which does not add “.InRequestScope()”

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 use Entity, ASP.NET and Hangfire, without getting all those transactions errors?

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

Looks like your SQL connection is leaked to multiple threads. Can you show the lines of code related to the kernel configuration?

Hello,

Thanks for the reply. Here’s Startup.cs

        GlobalConfiguration.Configuration.UseSqlServerStorage( "somestring" );

        GlobalConfiguration.Configuration.UseNinjectActivator( NinjectWebCommon.RegisterServiceForHangFire( new StandardKernel() ) );

        app.UseHangfireServer();
        app.UseHangfireDashboard( "/hangfire", new DashboardOptions {
            AuthorizationFilters = new[] { new HangfireAuthorizationFilter() }
        } );

NinjectWebCommon.cs

  public static IKernel RegisterServiceForHangFire ( IKernel kernel ) {
        kernel.Bind<ProjectMainContext>().ToSelf();

        kernel.Bind<IFilePathProvider>().To( typeof( HangfireFileSystemHelper ) );
        kernel.Bind<IProjectFactory>().To( typeof( ProjectWebFactory ) );

        kernel.Bind( typeof( IGenericRepository<> ) ).To( typeof( GenericRepository<> ) );

        kernel.Bind<ILoggedUserProvider>().To<HangFireLoggedUserProvider>();

        return kernel;
    }

    private static void RegisterServices ( IKernel kernel ) {
        kernel.Bind<ProjectMainContext>().ToSelf().InRequestScope();

        kernel.Bind<IFilePathProvider>().To( typeof( FileSystemHelper ) );
        kernel.Bind<IProjectFactory>().To( typeof( ProjectWebFactory ) ).InRequestScope();
        kernel.Bind( typeof( IGenericRepository<> ) ).To( typeof( GenericRepository<> ) ).InRequestScope();
    }

RegisterServices() is called by

  private static IKernel CreateKernel () {
        var kernel = new StandardKernel();

        Kernel = kernel;

        try {
            kernel.Bind<Func<IKernel>>().ToMethod( ctx => () => new Bootstrapper().Kernel );
            kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();

            System.Web.Http.GlobalConfiguration.Configuration.DependencyResolver = new Ninject.Web.WebApi.NinjectDependencyResolver( kernel );

            **RegisterServices( kernel );**
            return kernel;
        }
        catch {
            kernel.Dispose();
            throw;
        }
    }

Any inputs…?

Thanks!