Please considerer the following scenario :
- I have created a full-web application by using the ASP .NET MVC 3 framework. Now my application is managed by a web server.
- An HTTP request is received on the server-side of my application.
- A class implementing the singleton design pattern is instanciated on server-side.
- A response is sent to the browser.
- Another HTTP request is received on the server-side of my application. Is the singleton instance used at step 2 still available on server-side ?
I read some information about the life cycle of an ASP .NET application on this page : http://msdn.microsoft.com/en-us/library/ms178473.aspx
But I am still not able to answer my question.
Thanks in advance for your future help
I have just made some tests under VS2010.
Here is the list of the main components of my project :
- The Home controller containing an Index HttpGet action method.
- The view resulting from the Index action method.
- The SingletonTest class which implements the singleton design pattern.
Here is the code of the SingletonTest class :
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++;
}
}
Here is the code of the Index action method :
public ActionResult Index()
{
SingletonTest st = SingletonTest.Instance;
st.IncrementCounter();
return View();
}
Here is the code of the view :
@SingletonTest.Instance.Counter
Here the test scenario I have followed :
- The IIS server has been automatically launched by VS2010.
- I have requested the /Home/Index/ URL then the value 1 has been displayed.
- I have requested the /Home/Index/ URL then the value 2 has been displayed.
- ...
This test shows that the SingletonTest instance made at Step 1 is available when processing the next requests. I guess that a memory space is allocated to my web application on the server.
Then I have stopped the IIS server and I have followed my test scenario again. I have got the same results as before : 1, 2, ....
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.