2012-04-20 156 views
1

我一直在尋找這樣的代碼來創建一個基本的購物車,但缺點是,它使用一個靜態方法&因此(在添加到購物籃)購物車項目在會話之間共享。有人能指出如何修改ShoppingCart方法來消除這個限制嗎?C#購物車

Full Code reference is here

但是我相信這是有問題的代碼

// 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["ASPNETShoppingCart"] == null) { 
     Instance = new ShoppingCart(); 
     Instance.Items = new List<CartItem>(); 
     HttpContext.Current.Session["ASPNETShoppingCart"] = Instance; 
    } else { 
     Instance = (ShoppingCart)HttpContext.Current.Session["ASPNETShoppingCart"]; 
    } 
} 

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

public void AddItem(int productId) { 
    // Create a new item to add to the cart 
    CartItem newItem = new CartItem(productId); 

    // If this item already exists in our list of items, increase the quantity 
    // Otherwise, add the new item to the list 
    if (Items.Contains(newItem)) { 
     foreach (CartItem item in Items) { 
      if (item.Equals(newItem)) { 
       item.Quantity++; 
       return; 
      } 
     } 
    } else { 
     newItem.Quantity = 1; 
     Items.Add(newItem); 
    } 
} 
+0

如果您使用包含用戶特定數據的靜態變量,則所有用戶都將訪問該數據。 – Matthew 2012-04-20 17:08:40

+0

@David - 購物籃內容使用DES加密,然後發佈給第三方支付提供商並由其處理,所以是的,我知道ecommcerce的安全/ PCI方面。至於購買第三方解決方案,對於這樣一個小項目來說,這不是一個真正的選擇。 – 2012-04-20 19:05:00

+0

@Matthew,謝謝我也知道這一點:O) – 2012-04-20 19:05:31

回答

2

如果你使用靜態變量,那麼任何線程(無論哪個用戶),將有機會獲得這些數據。這意味着你基本上有一張購物卡在所有用戶之間共享,我懷疑你不想要。

相反,你可以有一個受保護的構造,以防止手工instanciation,然後要讀Session對象並獲取當前實例的靜態方法。至於你的靜態方法填寫你的Items列表,你應該在構造函數中做。

public static ShoppingCart GetInstance() 
{ 
    ShoppingCart cart = (ShoppingCart)Session["ASPNETShoppingCart"]; 

    if (cart == null) 
    { 
     Session["ASPNETShoppingCart"] = cart = new ShoppingCart(); 
    } 

    return cart; 
} 

protected ShoppingCart() 
{ 
    Items = new List<CartItem>(); 
} 
13

我已與一些商業購物車的工作,並存儲在他們車的每一個,甚至結帳前,在數據庫並只在會話中存儲會話標識。該SessionID被綁定到臨時購物車中的字段。

我強烈建議遵循相同的模式。假設你的網站非常受歡迎。將太多數據存儲在內存中(無論是在會話還是應用程序中),您將遇到問題。