First, you are creating a "utility" class that is derived from the page. This class will never be instantiated so it just won't work the way you are expecting it to.
The way I would normally attack a problem like this is:
- Create a class that serves as the base class for all the pages on which you want to use the shopping cart
- Put your shopping cart property in this class
- All pages that derive from the class will have access to the cart
- Make the property read-only and use an instantiate-on-demand pattern
Here's what your base class code should look like:
Code:
public abstract class SmartSessionPage : System.Web.UI.Page
{
private StoreCart _storeCart; //This is the local page instance
protected StoreCart ShoppingCart
{
get
{
if(_storeCart == null) //Is the local instance empty?
{
if(Session["ShoppingCart"] != null) //Is the cart in session?
{
_storeCart = (StoreCart)Session["ShoppingCart"]; //Get it from session
}
else //No cart in session
{
_storeCart = new StoreCart(); //Create new cart instance
Session["ShoppingCart"] = _storeCart; //Put it in session
}
}
return _storeCart;
}
}
}
Now, any page that you want to have access to the cart will need to inherit from your new class. For example:
Code:
public class SomePage : SmartSessionPage
{
protected void Page_Load(object sender, EventArgs e)
{
this.ShoppingCart.AddItem();
}
}
The GETTER for the ShoppingCart property does two important things:
- It checks to see that the local page instance hasn't already been set. If it is, it just returns it. This will always happen once per page life cycle.
- When the local instance hasn't been set, it checks to see if it's in session. If it is, it restores it from session into the local page instance so it's usable throughout the rest of the page cycle. If it isn't in session, it creates the new instance of the StoreCart and puts that into session.
The getter performs all the logic to create the shopping cart when it's needed so your individual pages don't have to worry about it.
-Peter