MrClan
MrClan

Reputation: 6780

What is the catch with ASP.NET singleton?

I went through a lot of links on stackoverflow, like this, this and this one too. Everywhere the answers suggest that, a static variable is static for entire app domain. That is exactly what I was expecting. But the behavior I'm observing is not so. Here's my code:

public static class CurrentGrid
{
    private static readonly Grid g;
    static CurrentGrid()
    {
        g = new Grid();
    }
    public static Grid Get { get { return g; } }
}

I call this from global.asax.cs AppStart method, like this:

if (Application["CurrentGrid"] == null)
    Application["CurrentGrid"] = CurrentGrid.Get;

I just want the Grid to be initialized ONCE, for entire app life time. But it is not happening. Every time, I get a new instance of Grid object. I tried, using

Application["CurrentGrid"] = new Grid()

but that too didn't work. As suggested in one of the answers in the above linked questions, I even moved the class definition from App_Start folder to the Models folder, but still the behavior remains the same. Finally I tried using a static constructor to initialize the Grid object just once, but still even this static constructor is fired everytime a new request comes.

Also, one another strange behavior that I see is, Application_Start() is called for every request too. I thought this method is invoked just once when the application starts for the first time. I guess, I'm mistaken in some very basic/core principles of OOP or ASP.NET framework, because I just can't find any explanation for this behavior. Thanks.

PS: 1) just a reminder that, my only objective here is to have a singleton Grid object for the entire application lifetime. 2) I'm doing all this inside a MVC5 and SignalR application (in case that matters).

PS: PROJECT ON GDRIVE

Upvotes: 3

Views: 417

Answers (2)

aleha_84
aleha_84

Reputation: 8539

Ensure you aren't writing any log entries (create or modify files) to the bin folder.

Upvotes: 3

Dion V.
Dion V.

Reputation: 2120

Perhaps this would help?

static CurrentGrid()
{
   if(g == null)
   {
      g = new Grid();
   }
}

Or maybe even better;

public static class CurrentGrid
{
    private static readonly Grid g;
    static CurrentGrid()
    {
        //Do Grid things her
    }
    public static Grid Get { 
                              get 
                              { 
                                if(g == null)
                                { 
                                   g = new CurrentGrid(); 
                                }

                                return g; 
                              } 
                           }
}

Doing it this way, you will definitely only get one Grid-object, unless you dispose it ofcourse.

Upvotes: -1

Related Questions