请考虑以下情况:
- 我使用 ASP .NET MVC 3 框架创建了一个完整的 Web 应用程序。现在我的应用程序由 Web 服务器管理。
- 在我的应用程序的服务器端收到一个 HTTP 请求。
- 实现单例设计模式的类在服务器端实例化。
- 向浏览器发送响应。
- 在我的应用程序的服务器端收到另一个 HTTP 请求。步骤 2 中使用的单例实例在服务器端是否仍然可用?
我在此页面上阅读了有关 ASP .NET 应用程序生命周期的一些信息:http: //msdn.microsoft.com/en-us/library/ms178473.aspx
但我仍然无法回答我的问题。
提前感谢您未来的帮助
我刚刚在VS2010下做了一些测试。
这是我的项目的主要组件列表:
- 包含 Index HttpGet 操作方法的 Home 控制器。
- 由 Index 操作方法产生的视图。
- 实现单例设计模式的 SingletonTest 类。
这是 SingletonTest 类的代码:
public class SingletonTest
{
private int counter;
private static SingletonTest instance = null;
public int Counter
{
get
{
return counter;
}
}
public static SingletonTest Instance
{
get
{
if (instance == null)
instance = new SingletonTest();
return instance;
}
}
private SingletonTest()
{
counter = 0;
}
public void IncrementCounter()
{
counter++;
}
}
这是 Index 操作方法的代码:
public ActionResult Index()
{
SingletonTest st = SingletonTest.Instance;
st.IncrementCounter();
return View();
}
这是视图的代码:
@SingletonTest.Instance.Counter
这是我遵循的测试场景:
- IIS服务器已经被VS2010自动启动了。
- 我已请求 /Home/Index/ URL,然后显示值 1。
- 我已请求 /Home/Index/ URL,然后显示值 2。
- ...
该测试表明,在处理下一个请求时,在步骤 1 中创建的 SingletonTest 实例可用。我想在服务器上为我的 Web 应用程序分配了一个内存空间。
然后我停止了 IIS 服务器,并再次遵循了我的测试场景。我得到了和以前一样的结果:1、2、....