DBContext 高性能实例创建

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");
    }
发布了89 篇原创文章 · 获赞 4 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/m0_37879526/article/details/104056097