2

I have a rather large SQL backed ASP.NET project that uses Entity Framework to interact with the database.

My question is, should I create an instance of the ObjectContext defined by the edmx/designer files in each class/method -or- wrap it around a static class that would instantiate onload and basically handle all requests through one instance.

I will have multiple users using the ObjectContext to read and update the DB, concurrency and thread safety are my utmost concerns.

EDIT: This code would ultimately run in IIS and be susceptible to recycling.

Matt
  • 24,106
  • 61
  • 180
  • 291

2 Answers2

1

In most cases you just need single context for every request. Only special scenarios can need more contexts per single request but never share context among requests.

Community
  • 1
  • 1
Ladislav Mrnka
  • 349,807
  • 56
  • 643
  • 654
0

The ObjectContext class is not thread safe. The integrity of data objects in an ObjectContext cannot be ensured in multithreaded scenarios.

Source: http://msdn.microsoft.com/en-us/library/system.data.objects.objectcontext.aspx

Therefore the best approach is to use an ObjectContext per HTTP request. Make a RepositoryBase class that every repository extends from and in the RepositoryBase define common CRUD operations (preferably generic) and make a new instance of only if it's null on requesting for it.

Matija Grcic
  • 11,718
  • 3
  • 59
  • 85