Is my singleton class unnecessary in my custom ASP.NET SessionStateStoreProvider?
I have written a custom SessionStoreProvider class that inherits from the Ses开发者_JS百科sionStateStoreProviderBase. 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?
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.
精彩评论