问题
I'm trying to use linq to sql for my project (very short deadline), and I'm kind of in a bind. I don't know the best way to have a data context handy per request thread.
I want something like a singleton class from which all my repository classes can access the current data context. However, singleton class is static and is not thread-safe and therefore not suitable for web apps. I want something that would create a data context at the beginning of the request and dispose of it along with the request.
Can anyone please share their solution to this problem? I've been searching for a solution and I've found a good post from Rick Strahl : http://www.west-wind.com/weblog/posts/246222.aspx but I don't completely understand his thread-safe or business object approach. If somebody has a simplified version of his thread-safe approach, i'd love to take a look.
回答1:
In the BeginRequest event of Global.asax you could store it in HttpContext.Current.Items which is sort of like a "session state" for the individual request. Each request gets it's own context so there's no threading issues if you are storing a new DataContext per request.
You can dispose it in the EndRequest event.
http://msdn.microsoft.com/en-us/library/system.web.httpcontext.items.aspx
However this will not scale well if you are going to be creating the DataContext on every request even if it doesn't get used. Instead you could make a static method that does lazy initialization.
(Sorry, typing this code on an iPhone... I know...)
private static MyDataContext GetDataContext() {
var dc = HttpContext.Current.Items["dc"] as MyDataContext;
if (dc==null) {
dc = new MyDataContext();
HttpContext.Current.Items.Add("dc", dc);
}
return dc;
}
来源:https://stackoverflow.com/questions/2481956/linq-to-sql-datacontext-for-a-web-application