Unexpected connection state when multiple requests at the same time

asp.net-core c# dependency-injection entity-framework-6

Question

We use ASP.NET Core and EF6 for database requests. Potentially, multiple user can access at the same time at the database. I materialized the situation with a unit test :

Parallel.For(0, 10, count => {
    result = userRepo.Sessions.Any(session => session.Token == token);
});

An exception is thrown : Unexpected connection state. When using a wrapping provider ensure that the StateChange event is implemented on the wrapped DbConnection.

This is something I completly understand : the code is trying to access to the database with the same connection in parallel, but the connection is closed before one request has finished. Ok, but with ASP.NET Core and Dependency Injection, the same connection can be shared between 2 requested, and so it can potentially crash like the test above. We use AddScoped for the registration of database services in DI container.

I there something I'm missing in our architecture ?

1
3
6/13/2016 3:59:23 PM

Accepted Answer

After a lot of investigations, we found the problem. We cached entire C# lambda expressions, which access to the database through Entity Framework, so from one HTTP request to another, the DbContext was the same, that's why this exception was thrown.

0
8/18/2017 8:08:05 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow