In the last few days, we are recording different exceptions thrown by entity framework (version 6) on our live stage, which only occur occasionally and show error messages, which all relate to the database connection.
Not allowed to change the 'ConnectionString' property. The connection's current state is closed.
The context cannot be used while the model is being created. This exception may be thrown if the context is used inside the OnModelCreating method or if the same context instance is accessed by multiple threads concurrently. Note that instance members of DbContext and related classes are not guaranteed to be thread safe.
Unexpected connection state. When using a wrapping provider ensure that the StateChange event is implemented on the wrapped DbConnection.
The underlying provider failed on Open.
We can not remember that we've changed anything and as already said these errors occur only sometimes. We can not reproduce them on local stage.
Does anyone have an idea what is going wrong or how to investigate?
Edit: It is an ASP.NET MVC 5 application which uses Unity IoC for instantiation. We use a self-written PerRequestLifeTimeManager which runs absolutely smooth in other mvc applications.
Thanks to the hint of @Gerd Arnold and @Chris Pratt I was able to figure out the root-cause of my issue.
Indeed the exceptions where caused by an instance of DbContext which was used concurrently accross multiple requests. This DbContext is part of an service which is injected by Unity property injection into an action filter. What I didn't know yet is that action filters don't get instantiated per request in APS.NET MVC but they are cached and reused. So do not inject instances of DbContext or DbContext-based classes into action filters!
We solved that issue by calling
DependencyResolver.Current.GetService<ClassType>() instead of using
Dependency-attribute in our filter's code to get an instance of the respective dependency (Please note that you lose the testability of the filter through this workaround)
It took me many hours to find the solution. To those users who occasionally encounter the same errors as mentioned in my question I would recommend check your appliation for any DbContext-based classes which might get used concurrently accross requests/threads.