Entity Framework DbContext上下文管理(HttpContext.Current.Items集合)

 Entity Framework DbContext上下文管理

   对DbContext对象的管理是实现会话唯一,但是会话不结束DbContext对象会一直被占用,也就导致数据库链接一直得不到释放,浪费资源.

  使用HttpContext.Current.Items集合存在DbContext对象,实现当一次请求来的时候创建DbContext对象(如果需要访问数据库),请求结束后立即释放(可以在Global.asax中添加Application_EndRequest事件及时释放)。

  

  HttpContext.Current.Items集合:是一个键值对集合,在HttpContext生存期在共享,其生存期很短,就是一次请求,当请求结束就会被销毁。

  

 1.DbContextHelper类封装:

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)
    {
        if (HttpContext.Current.Items.Contains(key))
        {
            HttpContext.Current.Items.Remove(key);
        }
    }
 
}

2.请求结束及时释放:在HttpContext管道事件中最后一个发生。

   void Application_EndRequest(object sender, EventArgs e)
    {
        DbContextHelper.DisposeDbContext("contextKey");
    }

猜你喜欢

转载自www.cnblogs.com/youguess/p/10516710.html