Using a Static Variable DataContext

I recently inherited an ASP.Net application using Linq2SQL. It currently has DataContext objects declared as static on each page, and I create them the first time I find that they are null (singleton, sort).

I need comments if this is good or bad. In situations where I only need to read from the database and in situations where I also need to write.

How to get only one instance of DataContext for the whole application?

+4
linq-to-sql datacontext
Apr 24 '09 at 16:05
source share
2 answers
I'm afraid that one DataContext for the application will work poorly. DataContext is not thread safe for beginners, so even using one of them as a static member of a page is a bad idea. As mentioned in asgerhallas, it’s ideal to use context for a unit of work — usually a single request. Everything else, and you will begin to find all your data in memory, and you will not see updates without an explicit update. Here are a few posts that speak to these two topics: Identity Maps and units of work
+6
Apr 24 '09 at 18:27
source share

I use one DataContext for each request, but it depends on the scripts that you encounter. I think the point with L2S was to use it with a single job template, where you have context for ... a zero unit of work. But in large applications this does not work well, since it is rather difficult to re-attach objects to a new context later.

Rick Strahl has a great introduction to this topic:

http://www.west-wind.com/weblog/posts/246222.aspx

One thing that I can say that I had problems with the past is to have one context for both reading and writing scripts. Tracking changes done in the datacontext is pretty overhead when you just read that most web applications usually do most of the time. You can make the datacontext readonly, and this will speed things up quite a bit - but then you need a different context for writing.

+4
Apr 24 '09 at 17:58
source share



All Articles