问题描述
在一个web应用程序,我需要有一类称为ProcessManager的只有一个实例。一种方法是,使之成为单身。另一种方法是使用对HttpApplicationState以确保我始终可以访问相同的情况下,像这样的:
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)applicationState["ProcessManager"];
}
}
哪种方法更好,为什么?
Which method is better and why?
推荐答案
根据您所提供的有限的描述,我会选择单身,因为那不会对HttpContext.Current的依赖,并且可以在ASP.Net管道外使用(例如,当你想要编写单元测试。)
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.)
(顺便说一句,当你设置东西放到ApplicationState,您还需要首先调用的就可以了,然后解锁(),它你完成写入后,以确保它是线程安全的。)
(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.)
另外,允许注射的HttpContext的,当你创建你ProcessManager的,这样你可以使用它与一个嘲弄的HttpContext。
Alternately, allow injection of an HttpContext when you create your ProcessManager, such that you can use it with a mocked HttpContext.
这篇关于辛格尔顿和对HttpApplicationState的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!