2

I have a strange issue, where basically i have a shopping cart using a session. When i deploy the site using IIS7 all looks fine. I add a product to the session on one pc and it displays in my basket. When i access the site from another pc the basket has this item in it!!??

its my understanding that a session instance is unique per user browser is this correct? and if so, how have i managed to do this? I know its probably something stupid but i can't figure it out, any help is much appreciated!

My session cart code is as follows

#region Singleton Implementation

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

        }

        protected ShoppingCart() { }

        #endregion
JazziJeff
  • 721
  • 4
  • 17
  • 35
  • Your session singleton implementation is wrong. See e.g. http://stackoverflow.com/questions/6076459/static-singleton-in-asp-net-session. You must not store the reference in static variable you should only return it. – IvanH Aug 20 '13 at 16:50

2 Answers2

5

You're storing a single static reference to a single global ShoppingCart.
This is a horrible idea.

Whenever you write ShoppingCart.Instance, it always returns the original value ou set in the static constructor.

You need to get rid of the singleton and always use session.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
2

It is because of public static readonly ShoppingCart Instance;

The instance always returns the same for everyone due to static (applies to application level).

Venkata Krishna
  • 14,926
  • 5
  • 42
  • 56