CodeFirstDBContext dbContext = null;
if(HttpContext.Current.Items["CodeFirstDBContext"]==null)
{
dbContext= new CodeFirstDBContext();
HttpContext.Current.Items["CodeFirstDBContext"] = dbContext;
}else
{
dbContext = HttpContext.Current.Items["CodeFirstDBContext"] as CodeFirstDBContext;
}
public class DbContextHelper
{
/// <summary>
/// 创建DBContext对象,并存放到HttpContext.Current.Items集合中。
/// </summary>
/// <returns></returns>
public static T CreateDbContext<T>(string key) where T : class, new()
{
T context = HttpContext.Current.Items[key] as T;
if (context == null)
{
context = new T();
HttpContext.Current.Items.Add(key, context);
}
return context;
}
/// <summary>
/// 释放DBContext对象
/// </summary>
public static void DisposeDbContext(string key) where T : class, new()
{
if (HttpContext.Current.Items.Contains(key))
{
T context = HttpContext.Current.Items[key] as T;
context.Dispose();
HttpContext.Current.Items.Remove(key);
}
}
}
请求结束及时释放:在HttpContext管道事件中最后一个发生。
void Application_EndRequest(object sender, EventArgs e)
{
DbContextHelper.DisposeDbContext("contextKey");
}