Pittsburgh DBA
Pittsburgh DBA

Reputation: 6772

ASP.Net - singleton class inside page class

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?

Upvotes: 0

Views: 360

Answers (2)

Nathan Anderson
Nathan Anderson

Reputation: 6878

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#

Upvotes: 1

ema
ema

Reputation: 5773

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

Upvotes: 3

Related Questions