LINQ to SQL的DataContext的Web应用程序 [英] linq to sql datacontext for a web application
问题描述
我试图使用LINQ to SQL中我的项目(很短的期限),我在困境是一种。我不知道有每个请求线程得心应手数据上下文的最好方法。
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.
我想是从我所有的资源库类可以访问当前数据上下文中的单例类。但是,单例类是静态的,是不是线程安全的,因此不适合于Web应用程序。我想要的东西,将在请求的开始创建一个数据上下文,并请求一起处置。
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.
谁能请分享自己解决这个问题?我一直在寻找一个解决方案,我发现从里克施特拉尔好的帖子:的 http://www.west-wind.com/weblog/posts/246222.aspx 但我不完全理解他的线程安全或业务对象的方法。如果有人有自己的线程安全方式的简化版本,我很想去看看。
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.
推荐答案
在Global.asax中的BeginRequest事件,你可以保存它HttpContext.Current.Items这有点像一个会话状态为单独的请求。每个请求得到它的自己的上下文,所以没有线程的问题,如果你存储每个请求一个新的DataContext。
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.
您可以配置它在EndRequest事件。
You can dispose it in the EndRequest event.
http://msdn.microsoft.com/ EN-US /库/ system.web.httpcontext.items.aspx
不过这不会很好地扩展,如果你打算在即使没有得到用它的每个请求被创建的DataContext。相反,你可以做,做延迟初始化的静态方法。
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.
(对不起,在iPhone上输入此code ......我知道...)
(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;
}
这篇关于LINQ to SQL的DataContext的Web应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!