views:

39

answers:

1

I have written a custom SessionStoreProvider class that inherits from the SessionStateStoreProviderBase. I have a class called SessionStore that serves a a Data Access Layer for the database I am using as the backend to store the session data. I've created a singleton instance property like below

   public static SessionStore Instance
    {
        get
        {
            if (instance == null)
            {
                lock (syncRoot)
                {
                    if (instance == null)
                        instance = new SessionStore();
                }
            }
            return instance;
        }
    }

Back inside my SessionStoreProvider methods I am instantiating the class like so

 var sessionStore = SessionStore.Instance;

My goal is to make sure that only one session store exists for a user session at one time. Is this a sound approach? Would this have any negative repercussions? Is there a better way to do this?

+1  A: 

Although double-check locking works for the majority of scenarios, making a static singleton work efficiently may require a little extra work:

public class SessionStore {
  /// <summary>
  /// Gets the current instance of <see cref="SessionStore" />.
  /// </summary>
  public static SessionStore Instance {
     get {
      return SessionStoreInternal.Instance;
    }
  }

  /// <summary>
  /// Supports lazy initialisation of a <see cref="SessionStore" /> instance.
  /// </summary>
  internal class SessionStoreInternal {
     /// <summary>
     /// The current instance of <see cref="SessionStore" />.
     /// </summary>
    internal static readonly SessionStore Instance = new SessionStore();

    /// <summary>
    /// Required to stop the Instance field being initialised through BeforeFieldInit     behaviour,
    /// allowing us to only initialise the field when it is accessed.
    /// </summary>
    static SessionStoreInternal() { }
  }
}

The reasoning behind this, is it allows us to manage a static singleton without having to create any locks. Creating a nested type like this will allow us to access the managed singleton knowing that the static constructor can be called at most once, when required, attributing to the lazy design concept.

Matthew Abbott
NM, I get the idea now.
CountCet