关于什么是Job Site Starter Kit,我就不多介绍了,MSDN上大把的介绍.
给个连接给大家慢慢参考吧:http://www.asp.net/Downloads/starter-kits/job/
下图是我改造后的程序结构:
主要是数据访问层的修改:
没有使用Linq自动生成的DBML文件,主要是它修改麻烦,垃圾太多.
我将DataContext和Model分开来放,这个代码结构更清楚,修改也容易.
对DataContext的管理,我采用了OpenSessionInView的方法.
在BeginRequest开始建立一个DataContext对象,并放在HttpContext中,EndRequest时,再关闭它.
实现很简单,自定义并注册一个HttpModule就行了.
主要的实现代码:
1: public class JobSiteLinqModule : IHttpModule
2: {
3: public void Dispose()
4: {
5: //throw new NotImplementedException();
6: }
7:
8: public void Init(HttpApplication context)
9: {
10: context.BeginRequest += new EventHandler(context_BeginRequest);
11: context.EndRequest += new EventHandler(context_EndRequest);
12: }
13:
14: void context_EndRequest(object sender, EventArgs e)
15: {
16: JobSite.Data.Context.JobDataContext dc =
17: HttpContext.Current.Items["JobDataContext"] as JobSite.Data.Context.JobDataContext;
18: if (dc != null)
19: {
20: HttpContext.Current.Response.Write("<h5>JobDataContext dispose...</h5>");
21: HttpContext.Current.Items.Remove("JobDataContext");
22: dc.Dispose();
23: }
24: }
25: void context_BeginRequest(object sender, EventArgs e)
26: {
27: //TODO:检查其他的一些axd也会当一次WebRequest
28: if (HttpContext.Current.Request.RawUrl.Contains("aspx"))
29: {
30: JobSite.Data.Context.JobDataContext dc = HttpContext.Current.Items["JobDataContext"] as JobSite.Data.Context.JobDataContext;
31: if (dc == null)
32: {
33: dc = CreateJobDataContext();
34: HttpContext.Current.Items["JobDataContext"] = dc;
35: HttpContext.Current.Response.Write("<h5>JobDataContext init...</h5>");
36: }
37: }
38: }
39: private JobSite.Data.Context.JobDataContext CreateJobDataContext()
40: {
41: HttpContext.Current.Response.Write("<h5>Create...</h5>");
42: JobSite.Data.Context.JobDataContext dc =
43: new JobSite.Data.Context.JobDataContext(ConfigurationManager.ConnectionStrings["job"].ConnectionString);
44:
45: dc.Log = Console.Out;
46: dc.Log = HttpContext.Current.Response.Output;
47: //dc.DeferredLoadingEnabled = false;
48:
49:
50: return dc;
51: }
52: }
运行效果:
代码下载: