c# shopping cart

kb. picture kb. · Apr 20, 2012 · Viewed 10.5k times · Source

I've been looking at this code to create a basic shopping cart, but the drawback is that it uses a static method & therefore the shopping cart items (when added to the basket) are shared across sessions. Can someone point out how to modify the ShoppingCart method to remove this restriction?

Full Code reference is here

but Im sure this is the offending code

// 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);
    }
}

Answer

David picture David · Apr 20, 2012

I've worked with several commercial shopping carts, and every single one of them stored the cart, even before checkout, in a DB and only stored a session ID in session. That SessionID was tied to as field in the temporary cart.

I'd strongly recommend following the same pattern. Suppose your site gets very popular. Storing too much data in memory (whether in Session or Application) you're going to run into issues.