FAQ Item: How do I control the lifetime of the DataContext?
Locked
-
Sunday, June 20, 2010 1:08 PMHow do I control the lifetime of the DataContext?
All Replies
-
Sunday, June 20, 2010 1:10 PM
Generally, DataContext is intended to be a short-lived object. It 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 or as a member of short-lived classes that represent a logical set of related database operations. However, we can also keep the life the entities longer and pass them between different DataContext objects if necessary, especially for some web applications. We can find many threads and blogs discussing this proble:
http://blogs.msdn.com/dinesh.kulkarni/archive/2008/04/27/lifetime-of-a-linq-to-sql-datacontext.aspx
However, it is not an absolute answer. Sometimes, we may need the DataContext instance to be kept longer. How to manage the lifetime of DataContext is determined by the detailed scenario of our applications. Rick Strahl (MVP) has a brilliant blog article discussing this topic:
http://www.west-wind.com/weblog/posts/246222.aspx
Rick concluded these different approaches to manage the DataContext:
-
Create a new Context for each atomic operation (Application level management)
-
Create a global DataContext and handle all operations against this single DataContext object
-
Create a thread specific DataContext
-
Create a per business object DataContext
- Marked As Answer by MSDN FAQ Sunday, June 20, 2010 1:10 PM
-

