2

I was warned not to use more than one DBEntityContext of the Entity Framework in my application. The reason being the risk of deadlock due to concurrent access to the database.

Can anybody confirm this? If this true is it a good idea to implement a Singleton object for the DBContext?

Any Articles on this issue are welcome.

Thank you Advance.

xelco52
  • 4,943
  • 4
  • 35
  • 55
CloudyMarble
  • 34,949
  • 69
  • 92
  • 126

2 Answers2

8

ObjectContext and DbContext are not thread safe. See http://msdn.microsoft.com/library/system.data.objects.objectcontext.aspx. If you use them in a multithreaded environment like ASP.NET, you are running in big trouble when using a single instance. It is recommended to use one ObjectContext per request. The ObjectContext has to be disposed at the end of the request. The Article Managing Entity Framework ObjectContext lifespan and scope in n-layered ASP.NET applications may be helpfull.

Is it possible, that you missunderstood your advisor who told you about deadlocks? May be he wants to warn you about possible deadlocks when using ObjectContext the wrong way.

brynhilde
  • 362
  • 1
  • 9
3

In web application you have to use a new context instance per each processed web request and dispose the instance after you don't need it any more. Context and anything related to EF is not thread safe. Moreover it implement unit of work and identity map patterns which makes other restrictions on using the context instance.

Dead locks can happen but that is something you must solve by correct transaction design.

Community
  • 1
  • 1
Ladislav Mrnka
  • 349,807
  • 56
  • 643
  • 654
  • Thank you for the Answer, good Link, but doesnt creatign a new Context per Request coast more Performance than having the contextobject for the App lifetime as a Singleton? – CloudyMarble Jun 12 '12 at 09:19
  • Got it, i just read your other answer til the End, it makes sence, even though if the Performance could be an issue. – CloudyMarble Jun 12 '12 at 09:23
  • So can I have a context per controller in ASP.NET MVC and dispose it at the controller disposal? – Shimmy Weitzhandler Jul 04 '13 at 03:55