Multithreading Entity Framework: The connection was not closed. The connection's current state is connecting Multithreading Entity Framework: The connection was not closed. The connection's current state is connecting multithreading multithreading

Multithreading Entity Framework: The connection was not closed. The connection's current state is connecting


Looks like your service, repository and context are supposed to live for the whole life time of your application but that is incorrect. You can have multiple timers triggered at the same time. That means multiple threads will use your service in parallel and they will execute the code of your service in their thread = context is shared among multiple threads => exception because context is not thread safe.

The only option is to use a new context instance for each operation you want to execute. You can for example change your classes to accept context factory instead of context and get a new context for each operation.


In case this helps anyone:

In my case, I did ensure that the non-thread-safe DbContext had a TransientLifetime (using Ninject), but it was still causing concurrency issues! Turns out that in some of my custom ActionFilters I used Dependency Injection to get access to the DbContext in the constructor, but ActionFilters have a lifetime that keeps them instantiated over multiple requests, so the context didn't get recreated.

I fixed it by manually resolving the dependency in the OnActionExecuting method instead of in the constructor so that it is a fresh instance every time.


In my case I was getting this problem because I forgot the await keyword before one of my DAL function calls. Putting await there resolved it.