2012-06-15 24 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"]; 
      } 
     } 
    }