开发者

How long should I keep my LINQ DataContext around? ASP.Net page

开发者 https://www.devze.com 2022-12-16 22:49 出处:网络
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

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.


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.


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).


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号