Random errors occur with per-request DbContext

asp.net-mvc, dbcontext, entity-framework, unity-container

Solution

After further investigation I found out that request processing thread sometimes steals DbContext from other thread, so Rashid's implementation of PerRequestLifetimeManager may not be thread safe. I moved to Unity.Mvc3 again and the errors disappeared, I must have made some mistake when I tried that last time.

The only error not related were deadlocks. They were caused by collision of

SELECT ... FROM X JOIN Y ... JOIN Z ...

and

BEGIN TRAN
UPDATE Z ...
UPDATE Y ...
COMMIT TRAN

SELECT locked Y and wanted Z, TRAN locked Z and wanted Y

Problem

I'm experiencing random errors (several per day) in my mvc+ef+unity application under higher load (10+ request per sec): - The connection was not closed / The connection's current state is connecting - deadlocks on Count queries (no explicit transaction) - An item with the same key has already been added. in System.Data.Entity.DbContext.SetTEntity while resolving DbContext - The remote host closed the connection. The error code is 0x80070057 - There is already an open DataReader associated with this Command which must be closed first. - I turned on MARS to get rid off this (altough I believe it should work correctly without MARS, there are no nested queries), which may caused another random error: - The server will drop the connection, because the client driver has sent multiple requests while the session is in single-user mode. I use this implementation of PerRequestLifetimeManager and tried Unity.Mvc3 too without any difference. There are some hints that DbContext is not being disposed correctly. I am not sure if per-request is the cause of problems, because it seems to be common practise.

Original source

Related problems