Multiples notifications, one enqueue - New transaction is not allowed because there are other threads running in the session

Hello, we got a stranger error when send multiples notifications from one enqueue. “New transaction is not allowed because there are other threads running in the session”. We use .NetCore 3.1 with Entity Framework, the error occur when the second notification is called.

First of all we using CQRS as architecture, so, for this error we have a event for many event handlers called by single enqueue. The first notification occur normally, the context of entity framework works well, but when that notification ends and Hangfire goes to the next one, the context of entity was null and the error above occurs.

The context i mentioned above is Microsoft.EntityFrameworkCore.DbContext as default of entity, but for some reason, when the error occurs if i call …DbContext.Database.GetDbConnection() we can see the SQL Connection is opened but the …DbContext.Database.CurrentTransaction is null.

We use AddDbContextPool in Program/Startup of Hangfire project.

I don’t know whats goes wrong, if someone have some ideas.

Thanks in advance.

Did you manage to fix this?

Yes, but first of all, adding more info, this error only occur when uses tests project.

I’ve a create a adpater in Handle classes.
Istead call my Application layer who have Hangfire extensions, now i call the API to make my tests do full cycle of my WebApplication. On the other hand, my tests increase the time of execution, cause now i call a adpter that (in some cases) converts Commands, Queries or Events queries to Request API query and call the API.

The root cause of the problem i never found!

Thanks in advance. I’m having the same error as you. I use HangFire to run some tasks concurrently, and those tasks use the same Entity Framework Db Context and cause transaction errors. Are there ways to implement multiple db context instances in order to run those tasks currently or is it impossible in the case of entity framework? Thanks once again.

Which version of .NET you are using? 3.1 or newest 6?

I’ve migrated the version to 6 and i must change my db factory classes, instead use AddDbContextPool now we using AddBdContextFactory, therefore i don’t need to handle in my Contexts classes the “dispose” context, now the AddBdContextFactory handle by himself.

This thing could fix the problem, but as i hade created my adpter clases, i don’t know if this little change could fix the problem.

I’m using .NET6. I found out that I actually use the same instance for multiple transactions that cause transaction errors. Is it possible to run httpcontext to run the jobs?