tags:

views:

85

answers:

1

Hi,

I created a Singleton class in c#, with a public property that I want to initialize when the Singleton is first called.

This is the code I wrote :

public class BL
{
    private ISessionFactory _sessionFactory;
    public ISessionFactory SessionFactory
    {
        get { return _sessionFactory; }
        set { _sessionFactory = value; }
    }

    private BL()
    {
        SessionFactory = Dal.SessionFactory.CreateSessionFactory();
    }

    private object thisLock = new object();

    private BL _instance = null;
    public BL Instance
    {
        get
        {
            lock (thisLock)
            {
                if (_instance == null)
                {
                    _instance = new BL();
                }
                return _instance;
            }
        }
    }
}

As far as I know, when I address the Instance BL object in the BL class for the first time, it should load the constructor and that should initialize the SessionFactory object.

But when I try : BL.Instance.SessionFactory.OpenSession(); I get a Null Reference Exception, and I see that SessionFactory is null...

why?

+3  A: 

This is not a singleton. You should refer to Jon Skeet's excellent guide on singletons in C#. For example, use this pattern:

public sealed class Singleton
{
    static readonly Singleton instance=new Singleton();

    // Explicit static constructor to tell C# compiler
    // not to mark type as beforefieldinit
    static Singleton()
    {
    }

    Singleton()
    {
    }

    public static Singleton Instance
    {
        get
        {
            return instance;
        }
    }
}

Notice in particular that instance is static.

Mark Byers
ok, and then where should i put the initation of the ISessionFactory object i have (Dal.SessionFactory.CreateSessionFactory();) ??
gillyb
@gillyb: It looks like it shoud be a readonly instance member of the class, initialized in the constructor. You probably want to read this first though: http://stackoverflow.com/questions/185384/order-of-static-constructors-initializers-in-c
Mark Byers