LINQ to SQL - where does your DataContext live? LINQ to SQL - where does your DataContext live? asp.net asp.net

LINQ to SQL - where does your DataContext live?


The guidelines from the MSDN documentation on the DataContext class are what I would recommend following:

In general, a DataContext instance is designed to last for one "unit of work" however your application defines that term. A DataContext is lightweight and is not expensive to create. A typical LINQ to SQL application creates DataContext instances at method scope or as a member of short-lived classes that represent a logical set of related database operations.

Because DataContext is IDisposable, I find it easiest to create and use a DataContext in a using statement within one method, so it can be disposed of properly.

Also note that "any instance members are not guaranteed to be thread safe", so sharing one DataContext between multiple threads would be unwise.


Dependency Injection.

We prefer to keep our business layer ignorant of web vs non-web scenario's. Instead, business logic layer objects take a DataContext reference in their constructor which (explicitly) allows sharing the DataContext and (implicitly) allows sharing of the entity objects from query results as they are all from the same data context.

Also DataContexts implement IDisposable, so you really need to manage their lifetime. All our web forms have a base class, and part of that is a datacontext property (lazily created). That way everything on a page can share it, which is most often the case. The context is disposed of manually in the page's OnUnload() event.


  • You shouldn't mix linq entities from from different data contexts, and you typically get into trouble if you use the linq entities if the datacontext has been Dispose()'d of.


I'm using a per-thread context. It is tricky to setup, but it cleans up everything that needs to talk to the db.