user5550554
user5550554

Reputation:

Singleton instance is always null

I have an ASP.net with MVC program with the current singleton class:

    public sealed class Foo
{
    private static volatile Foo_instance;
    private static object syncRoot = new Object();
    private List<Obj> _objList;

    private Foo()
    {
        _objList = new List<Obj>();
    }

    public static Foo Instance
    {
        get
        {
            if (_instance == null)
            {
                lock (syncRoot)
                {
                    _instance = new Foo();
                }
            }
            return _instance;
        }
    }
    public void AddObjToList(Obj _object)
    {
        lock (_instance)
        {
            _objList.Add(_object);
        }
    }   
    public void FindAndRemoveObj(string id) 
    {
        lock (_instance)
        {
            Obj _object = null;
            _object= _objList.FirstOrDefault(t => t.UniKey == id);
            if (_object!= null) 
            {
                _objList.Remove(object);
            }
        }
    }
}

The first time that a class get the instance of this class it will return a new/clean instace of foo class, as expected, and then populating the list however a second class that will remove itens from the same list is receveing an new instance with an empty list.

Upvotes: 0

Views: 1921

Answers (2)

user5550554
user5550554

Reputation:

The conclusion was that the asp.net is creating new instances of the domain and that causes a new singleton object each time. I have searched how to sync objects between domains but that is too "workaround" for me, so I decided to add a boolean column that update the value with the confirmation or failure.

Thanks everyone

Upvotes: 0

Phil
Phil

Reputation: 125

This code has the lock in the wrong place:

if (_instance == null)
{
    lock (syncRoot)
    {
        _instance = new Foo();
    }
}

As thread 1 creates _instance, a second thread will block on the lock, then create _instance anew when it is released.

Another thing to be careful about it that you should never rely on static variables in IIS across server lookups. The application pool can be recycled at any time.

Upvotes: 1

Related Questions