2013-01-22 40 views

回答

1

你应该担心的是创建DbContext,因为这很贵。 我通常每个请求使用一个DbContext,而不是在任何地方创建多个DbContext实例。

我将它存储在HttpContext对象中,并在请求结束时处理它。

你可以在它身上找到here

更多信息请看下面我修改实施。 (原始来自上面的链接并使用ObjectContext)。

我的上下文类

using System.Data.Entity; 
using System.Data.Objects; 
using System.Web; 
using Fot.Admin.Models; 

namespace Context 
{ 
    public static class ContextManager 
    { 
     internal const string DB = "MY_DB_CONTEXT"; 

     /// <summary> 
     /// Get an instance that lives for the life time of the request per user and automatically disposes. 
     /// </summary> 
     /// <returns>Model</returns> 
     public static T AsSingleton<T>() where T : DbContext, new() 
     { 
      HttpContext.Current.Items[DB] = (T)HttpContext.Current.Items[DB] ?? new T(); 
      return (T)HttpContext.Current.Items[DB]; 
     } 


    } 
} 

我的上下文模块

using System; 
using System.Data.Entity; 
using System.Data.Objects; 
using System.Web; 

namespace Context 
{ 
    /// <summary> 
    /// Entity Module used to control an Entities DB Context over the lifetime of a request per user. 
    /// </summary> 
    public class ContextModule : IHttpModule 
    { 
     private const string DB = ContextManager.DB; 


     void context_EndRequest(object sender, EventArgs e) 
     { 
      Dispose(); 
     } 


     #region IHttpModule Members 

     public void Dispose() 
     { 
      if(HttpContext.Current != null) 
      { 
       if (HttpContext.Current.Items[DB] != null) 
       { 
        var entitiesContext = (DbContext) HttpContext.Current.Items[DB]; 

        entitiesContext.Dispose(); 
        HttpContext.Current.Items.Remove(DB); 

       } 

      } 
     } 

     public void Init(HttpApplication context) 
     { 
      context.EndRequest += new EventHandler(context_EndRequest); 
     } 

     #endregion 

    } 
} 

在我的web.config <httpModules>下我添加此下方。

<add name="ContextModule" type="Context.ContextModule" /> 

这可以确保在每个请求之后调用end_Request,以便您可以正确地处理上下文。

当你需要DbContext的用法如下。

var Context = ContextManager.AsSingleton<MyDBContext>(); 
+0

在我的工作单元实现中,我有一个DbContext属性,并且将相同的DbContext传递给存储库构造函数。这是否意味着我在DbContext上使用? –

+0

并且您是否有如何在HttpContext中存储DbContext的示例?谢谢。 –

+0

这是不正确的 - DbContext实例化并不昂贵。 – Pawel