【发布时间】:2011-10-13 23:00:41
【问题描述】:
因此,我从另一位开发人员那里接手了一个 VB.net Web 应用程序项目,并发现迄今为止编写的代码存在一个明显的问题。
开发者根据本教程(http://net.tutsplus.com/tutorials/other/build-a-shopping-cart-in-aspnet/)构建了一个购物车应用程序。
注意:对于任何考虑将此作为生产 ASP.net 购物车的基础的开发人员 - 不要 - 继续阅读以了解更多信息......
编写该教程的人意识到,对于基于会话的购物车来说,使用 Singleton 并不是一个非常聪明的模式,但为时已晚。事实上,它很愚蠢——真的很愚蠢。使用这种模式,每个用户都有相同的购物车实例!
教程中有许多有用的 cmets 介绍了如何将 Singleton 实例会话转换为对象(例如作者:http://net.tutsplus.com/tutorials/other/build-a-shopping-cart-in-aspnet/comment-page-1/#comment-56782)。
但我的应用程序使用 VB.net 等效项(可在该页面上的下载文件中获得),我想知道我是否需要遍历整个应用程序并删除对以下内容的所有引用:
ShoppingCart.Instance.AddItem
并手动将它们替换为:
Dim cart As ShoppingCart = ShoppingCart.GetShoppingCart()
cart.AddItem(3)
或者有什么更聪明的方法可以转换这段代码:
#Region "Singleton Implementation"
' Readonly variables can only be set in initialization or in a constructor
Public Shared ReadOnly Instance As ShoppingCart
' The static constructor is called as soon as the class is loaded into memory
Shared Sub New()
' 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") Is Nothing Then
Instance = New ShoppingCart()
Instance.Items = New List(Of CartItem)
HttpContext.Current.Session("ASPNETShoppingCart") = Instance
Else
Instance = CType(HttpContext.Current.Session("ASPNETShoppingCart"), ShoppingCart)
End If
换成别的东西,所以我不需要更改实例调用?
例如类似这样的东西(这是我在文章的另一条评论中找到的 C# 代码 sn-p - 我需要一个 VB.net 等价物,但我不知道如何编写它 - 我的 VB.net 有点生疏了! )
public static ShoppingCart Instance
{
get
{
ShoppingCart c=null;
if (HttpContext.Current.Session["ASPNETShoppingCart"] == null)
{
c = new ShoppingCart();
c.Items = new List();
HttpContext.Current.Session.Add(“ASPNETShoppingCart”, c);
}
else
{
c = (ShoppingCart)HttpContext.Current.Session["ASPNETShoppingCart"];
}
return c;
}
}
感谢您提供的任何帮助。
埃德
【问题讨论】:
-
有哪些存储选项?是全部在内存中还是由 SQL 等支持...?
-
@bryanmac 很公平 :) 我不是故意不接受答案。
-
@bryanmac - 我被 Inproc(内存)卡住了 - 我有一个只支持 Inproc 的 CMS(它显然不能序列化会话数据)
标签: session singleton instance