2

请考虑以下情况:

  1. 我使用 ASP .NET MVC 3 框架创建了一个完整的 Web 应用程序。现在我的应用程序由 Web 服务器管理。
  2. 在我的应用程序的服务器端收到一个 HTTP 请求。
  3. 实现单例设计模式的类在服务器端实例化。
  4. 向浏览器发送响应。
  5. 在我的应用程序的服务器端收到另一个 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

这是我遵循的测试场景:

  1. IIS服务器已经被VS2010自动启动了。
  2. 我已请求 /Home/Index/ URL,然后显示值 1。
  3. 我已请求 /Home/Index/ URL,然后显示值 2。
  4. ...

该测试表明,在处理下一个请求时,在步骤 1 中创建的 SingletonTest 实例可用。我想在服务器上为我的 Web 应用程序分配了一个内存空间。

然后我停止了 IIS 服务器,并再次遵循了我的测试场景。我得到了和以前一样的结果:1、2、....

4

2 回答 2

0

Even though the singleton may persist across multiple requests you need to be careful for exactly the reasons of your second test - when IIS is restarted or the app pool is recycled everything will be lost.

Are you sure that you need a singleton instance?

If you're looking to persist some state across all requests it would be better to use an external storage such as a database.

于 2012-01-11T17:07:42.067 回答
0

IIS 将创建以处理并发请求的同一应用程序的多个实例呢?

如果 IIS 在高流量情况下创建同一应用程序的多个实例,我认为单例对象将不一样

于 2013-02-05T01:02:42.993 回答