2012-06-15 27 views
0

我SHOPING車應用程序我使用下面的代碼,以保持Cart.There舉行會議一個錯誤,當我打開我的網站在更多然後到瀏覽器有會議衝突,當我從我的一個瀏覽器,然後選擇到另一個項目,所以先前創建的會話更新 ,但必須有每個瀏覽器的新會話 請有人幫助我瞭解會話中的錯誤的區域。我對着會話衝突錯誤在我的網站

#region Singleton Implementation 

    // Readonly properties can only be set in initialization or in a constructor 
    public static readonly ShoppingCart Instance; 
    // The static constructor is called as soon as the class is loaded into memory 
    static ShoppingCart() 
    { 
     // If the cart is not in the session, create one and put it there 
     // Otherwise, get it from the session  
     if (HttpContext.Current.Session["ShoppingCart"] == null) 
     { 
      Instance = new ShoppingCart(); 
      Instance.Items = new List<CartItem>(); 
      HttpContext.Current.Session.Add("ShoppingCart", Instance); 
     } 
     else 
     { 
      Instance = (ShoppingCart)HttpContext.Current.Session["ShoppingCart"]; 
     } 
    } 

    // A protected constructor ensures that an object can't be created from outside 
    protected ShoppingCart() { } 

    #endregion 

回答

1

靜態構造函數將被稱爲only once。所以其他人永遠不會執行。

而是這種實現的,你可以使用檢查,如果會話爲null,創建一個實例的屬性,否則返回所存儲的一個。

public Instance 
{ 
set{ ... } 
get{ ... } 
} 
+0

的聲明謝謝親愛的,但我得到了解決方案。 –

0

我發現有當我使用靜態構造函數中ShopingCart類的構造函數 問題直接我成爲全球這是與其他用戶街上購物車 共享方式我SHOPING車的數據,但我現在用的。那就是這樣的對象的性質,

* 的主要事情是在返回類型,如果獲取屬性*

public static ShoppingCart Instance 
    { 
     get 
     { 
      if (HttpContext.Current.Session["ShoppingCart"] == null) 
      { 
       // we are creating a local variable and thus 
       // not interfering with other users sessions 
       ShoppingCart instance = new ShoppingCart(); 
       instance.Items = new List<CartItem>(); 
       HttpContext.Current.Session["ShoppingCart"] = instance; 
       return instance; 
      } 
      else 
      { 
       // we are returning the shopping cart for the given user 
       return (ShoppingCart)HttpContext.Current.Session["ShoppingCart"]; 
      } 
     } 
    }