views:

129

answers:

4

I'm working on a ASP.Net webform app and I am wondering how long I should keep my data context around. Currently I create a context on each page load, and that context is used in every db access for the entire page load. Should I be using a context only in each method that needs it, and dispose at the end of the method? I understand that I can't access a object retrieved from the context once I exit that context's using block, but this isn't an issue with my design.

+1  A: 

I've done it the way you described as well as another way which is bound and destroyed based on the HTTP Request. That was allows a single page to use one DataContext from start to finish.

Overall, I haven't seen a big hit to performance doing it the way you're currently doing it.

hunter
+1  A: 

I'd say that you keep the context as long as you need it and it's appropriate. There's a balance to be drawn between life span of the context and the number of requests being made.

You don't want to create the context with every request to the database, similarly you probably don't want to maintain context for the entire life of the application (where that's possible).

I'd look at the effective transactions that the code is performing and look to have the context maintained within each of those. This granularity should also help with ensuring that your code is modular and extensible (as dependencies should be fewer).

Lazarus
+2  A: 

Steve Sanderson (author of Pro ASP.NET MVC Framework) has an interesting blog post on this issue. The gist of it is that the DataContext should be kept around per "unit of work", which basically correlates to a "request". I guess you could get away with shorter lifespans if you weren't modifying object and had no need to persist (update) any changes back to the DB.

You may also want to check out 'When should I dispose of a data context?' here on SO.

Dan Diplo
A: 

Take into account that an opened DataContext keeps an open connection to the sql server. If you want to retrieve data over multiple requests, rely on Identity Map to maintain the list of objects that are retrieved by older request. Hence, a DataContext should be kept alive only while fetching/updating from/into the database.

lmsasu
I'm not sure this is true (regarding keeping connection open). According to offical LinqToSql FAQ: "A connection typically remains open until you consume the query results." http://msdn.microsoft.com/en-us/library/bb386929.aspx
Dan Diplo
That's new for me.. thanks, I'll have a look at this.
lmsasu