Singleton object destroys in ASP.NET MVC

507 views Asked by At

I need to do some updates just once after starting ASP.NET MVC application. I've created the singleton instance:

public sealed class SingletonClass
{
    private static readonly Object s_lock = new Object();
    private static SingletonClass instance = null;

    private SingletonClass()
    { }

    public static SingletonClass Instance
    {
        get
        {
            if (instance != null) return instance;

            Monitor.Enter(s_lock);
            SingletonClass temp = new SingletonClass();
            temp.isSomeDataUpdated = false;
            Interlocked.Exchange(ref instance, temp);
            Monitor.Exit(s_lock);
            return instance;
        }
    }

    private bool isSomeDataUpdated;

    public void RefreshIfFirstExecution()
    {
        if (!isSomeDataUpdated) 
        { 
            isSomeDataUpdated = true;
            Refresh(); 
        }
    }

    private void Refresh() { ... }
}

and tried to execute it's RefreshIfFirstExecution() method, first from Global.asax --> Application_Start() method, then from Startup.cs --> Configuration(), even from BaseController's constructor. But I've got the same problem: after home page was displayed, when I try to navigate any next page, my instance object equals null again.

What have I done wrong and how to execute Refresh() method only once after application starting?

Updated

The instance begin include object, when I've changed the way of calling:

SingletonClass.Instance.RefreshIfFirstExecution();

to

var singletonRefresher = SingletonClass.Instance;
singletonRefresher.RefreshIfFirstExecution();

but isSomeDataUpdated equals false even after first execution of RefreshIfFirstExecution() method (which sets it to true). isSomeDataUpdated variable is the part of class (and, as result, the part of instance). As I understand, after first RefreshIfFirstExecution() it should be always true, am I right? What have I missed?

Updated2:

SingletonClass.Instance becomes null for every new request, BUT(!) if I move mouse over it in debug mode, it generates new object (breakpoint on Instance's get{} method doesn't trigger). I've returned back to the question "Why the SingletonClass.Instance object equals null?"

P.S. Alexey's singleton implementation haven't solved this problem

0

There are 0 answers