开发者

Singleton constructor question

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

开发者_Python百科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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜