In a web app, I need to have only one instance of a class called ProcessManager. One way is to make it a singleton. The other way is to use the HttpApplicationState to make sure I always access the same instance, like this:
public static ProcessManager ProcessManager
{
get
{
HttpApplicationState applicationState = HttpContext.Current.Application;
if (applicationState["ProcessManager"] == null)
{
applicationState["ProcessManager"] = new ProcessManager();
}
return (ProcessManager)a开发者_运维技巧pplicationState["ProcessManager"];
}
}
Which method is better and why?
Based on the limited description you've given, I would choose a Singleton, because then it doesn't have a dependency on HttpContext.Current, and can be used outside of the ASP.Net pipeline (for example, when you want to write unit tests.)
(As an aside, when you set something into ApplicationState, you also need to first call Lock() on it, and then Unlock() it after you're done writing to it, to make sure it's thread safe.)
Alternately, allow injection of an HttpContext when you create your ProcessManager, such that you can use it with a mocked HttpContext.
if you plan to implement it as singleton,as per Jon Skeet (a.k.a C# guru),he personally prefers the code below
public sealed class Singleton
{
static readonly Singleton instance=new Singleton();
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Singleton()
{
}
Singleton()
{
}
public static Singleton Instance
{
get
{
return instance;
}
}
}
(I'm assuming your ProcessManager constructor is private.)
Making it an actual singleton would be best, because such an approach would make it structurally impossible for other programmers that are maintaining your code to accidentally create multiple instances. There's nothing stopping a consumer from accessing the HttpApplicationState directly and removing and replacing the ProcessManager instance. So you must rely on convention to protect the instance of ProcessManager in HttpApplicationState.
Only if there is an actual use case for multiple instances of the class to exist does it make sense to allow multiple instantiations while relying on convention to protect the instance in HttpApplicationState.
精彩评论