0

I implemented a singleton class as a private class contained within my page. In the singleton, I store some data in a volatile variable. The issue is that the member variable retains its value between page executions. My assumption was that the class would be re-initialized upon first use during each page execution.

Why does it behave this way, and what should be done about it?

Pittsburgh DBA
  • 6,672
  • 2
  • 39
  • 68
  • Some code showing the definition and instantiation of the class would be helpful. – lance May 31 '11 at 15:27
  • Why not use `Session` or the `Cache`? – David Neale May 31 '11 at 15:35
  • Thank you. I have updated the code to place the data into the HttpContext.Current.Session. Basically, I wanted a Singleton pattern for conciseness of code throughout the page, but I wanted it to be per-page-execution (it is a collection of data that is expensive to retrieve, but should not be kept from page to page). – Pittsburgh DBA May 31 '11 at 15:49

2 Answers2

3

If the singleton instance is defined static it will be scoped as an application variable. The static scope is like global variable.

ema
  • 5,668
  • 1
  • 25
  • 31
1

Your class is most likely marked as 'static', so what you are seeing is a side-effect of this. From Static Classes and Static Class Members:

A static constructor is only called one time, and a static class remains in memory for the lifetime of the application domain in which your program resides.

So what you are seeing is intended behavior. Your singleton's private members remain in their previous state because the class remains in the application's memory. If you want to keep your singleton pattern in place but want a "fresh" state when calling one of it's methods, you could reset the values of any private member variables the method accesses.

Here is a good discussion on when to use static classes that you might be interested in:

When to use static classes in C#

Community
  • 1
  • 1
Nathan Anderson
  • 6,768
  • 26
  • 29