2012-04-09 54 views
2

我一直在努力實現與實體框架4.1,它實例上的Application_BeginRequest中的DbContext一個新的MVC3項目中的任何問題,並配置它Application_EndRequest是否有與使用靜態屬性返回的DbContext

protected virtual void Application_BeginRequest() 
    { 
     HttpContext.Current.Items["_EntityContext"] = new EntityContext(); 
    } 

    protected virtual void Application_EndRequest() 
    { 
     var entityContext = HttpContext.Current.Items["_EntityContext"] as EntityContext; 
     if (entityContext != null) 
      entityContext.Dispose(); 
    } 

該的EntityContext類的定義如下:

public class EntityContext : MyEntities, IDisposable 
{ 
    **//should this be static?** 
    public static EntityContext Current 
    { 
     get { return HttpContext.Current.Items["_EntityContext"] as EntityContext; } 
    } 



    void IDisposable.Dispose() 
    { 
     Current.Dispose(); 
    } 

我的問題是,將定義我目前的財產爲靜態造成任何問題在多用戶的情況?

+0

相關http://stackoverflow.com/questions/6987908/what-is-the-best-way-to-instantiate-and-dispose-dbcontext-in-mvc/6990244#6990244 – Eranga 2012-04-10 00:28:48

回答

-1

您在DbContext上的生命週期太長了。每個請求最少應有一個,每個訪問數據庫最好一個。

-1

正如insta指出的那樣,當你實際上need它應該實例化上下文。長時間使您的上下文壽命沒有優勢。

作爲一個側面說明,不需要明確調用Dispose方法,因爲.NET垃圾收集器將爲您更高效地執行此操作。

您可以爲每個類實例上下文,因爲您使用的是MVC,每個Controller實例上下文一次。

public class MyTableObjectController : Controller 
{ 
    MyContext context = new MyContext(); 

    public ActionResult Index() 
    { 
     var model = context.MyTableObjects; 

     return View(model); 
    } 
} 

我可能會問,你爲什麼試圖保持開始和結束請求之間的上下文可用?你想避免實例化嗎?

+0

這是一個很好的問題。我們試圖避免的問題是當我們引用該對象時可怕的「dbcontext已被處置」。如果這是更好的方法,我願意在控制器中實例化上下文。 – jazza1000 2012-04-09 23:54:14

+0

@ jazza1000我也有理解爲什麼當我第一次開始使用MVC 3時處置上下文的問題。也許這個問題的答案(http://stackoverflow.com/questions/5360372/)將幫助你。 – 2012-04-10 00:01:50

+0

您可能想要測試我的建議,您可能不想在實際項目中「嘗試」它,但始終可以製作一個新的小型項目並對其進行測試,以瞭解它的行爲方式以及是否適合使用該方法。 – Esteban 2012-04-10 18:48:20