views:

165

answers:

3

I am building a web application which uses an externally built class to handle much of the work and rules for the site. Most pages will require access to this class to get the information it needs to display. In the past I would put such a class in a session variable, so it's easily accessible when required and not need to be continually re-instantiated.

First Question, is this a bad idea to stuff this class into a session variable (it's not very big)?

Second question, if it's not a bad idea to store the sites app layer class in a session, then is there a way I can write a centralized method to use to grab or store the class into the session? I don't want to use a bunch of repeated code page after page getting the class, checking its there, creating if it's not, etc.

A: 

Without knowing any frameworks you use, it does not seem smart idea to put a class into the session store - it will be copied once per user - unless it has data that is unique to that user.

The best advice I can give would be to have a singleton class (you can google it - it is a design pattern) and then just have a function in that class that will return the class you need, or create it if it doesn't yet exist.

tomjen
+2  A: 

Before deciding on where to store your class, you have to answer two questions:

  1. How long this class should live?
  2. In what scope should it be visible?

Examples that answer both questions: request, user session, application.

If this class is stateless (no data and only logic), then it can probably live during the whole life of application. If this is just data unique to each user (that should not be reloaded on each request), then you can put it directly into session and skip following paragraphs.

Now, after you decided on life length, you have several solutions. The best solution for lifestyle management is an IoC container. The simpler solution is just to abstract storage and use a static facade, like Current.MyClass, where MyClass instance is stored in request, session or application depending on what storage was provided to Current.

You should not implement singleton in the specified class, however, since it should not itself decide how many instances you need and it limits your ability to replace is with another class with same interface if required.

Andrey Shchekin
A: 

The jury is still out on if the class should be stored in the session in the first place. With the app I asked the question for, I opted on NOT stuffing the class into session, it really wasn't necessary, I was being lazy. Working out this method to manage the session was worth all the time, as it's something that has bothered me for some time in web development.

What came out of my research is writing a static class to manage my session variables. This class handles all reads and writes to the session and keeps them all strongly typed for me to boot. It has always bothered me using repeated code all over the place for session crap. Keeps typos way down too.

There are two articles I like which I found on this, I can only locate one of them now and will include the other when I locate it.

The first was at Code Project This may be the second link

The pattern is easy and straight forward. I have also built a class for requests for grabbing parameters from url query strings. I see no reason not to extend it to cookies too.

This was my first use of the pattern, I only used strings so the private method is a bit limited, but this can easily be changed to use any class or primitive type.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;

namespace BDZipper.Site
{
    /// <summary>
    /// This class maintains all session variables for us instead of handeling them 
    /// individually in the session.  They are also strongly typed.
    /// </summary>
    public static class SessionManager
    {

        # region Private Constants
        // Define string constant for each property.  We use the constant to call the session variable
        // easier not to make mistakes this way.
        // I think for simplicity, we will use the same key string in the web.config AppSettings as
        // we do for the session variable.  This way we can use the same constant for both!
        private const string startDirectory = "StartDirectory";
        private const string currentDirectory = "CurrentDirectory";

        # endregion

        /// <summary>
        /// The starting directory for the application
        /// </summary>
        public static string StartDirectory
        {
            get
            {
                return GetSessionValue(startDirectory, true);
            }
            //set
            //{
            //    HttpContext.Current.Session[startDirectory] = value;
            //}
        }

        public static string CurrentDirectory
        {
            get
            {
                return GetSessionValue(currentDirectory, false);
            }
            set
            {
                HttpContext.Current.Session[currentDirectory] = value;
            }
        }
        //TODO: Update to use any class or type
        /// <summary>
        /// Handles routine of getting values out of session and or AppSettings
        /// </summary>
        /// <param name="SessionVar"></param>
        /// <param name="IsAppSetting"></param>
        /// <returns></returns>
        private static string GetSessionValue(string SessionVar, bool IsAppSetting)
        {
            if (null != HttpContext.Current.Session[SessionVar])
                return (string)HttpContext.Current.Session[SessionVar];
            else if (IsAppSetting)  // Session null with appSetting value
                return ConfigurationManager.AppSettings[SessionVar];
            else
                return "";
        }
    }
}
Brettski