代码之家  ›  专栏  ›  技术社区  ›  gillyb

单例构造器问题

  •  2
  • gillyb  · 技术社区  · 15 年前

    我在c_中创建了一个singleton类,在第一次调用singleton时要初始化一个公共属性。

    这是我写的代码:

    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;
                }
            }
        }
    }
    

    据我所知,当我第一次在bl类中处理实例bl对象时,它应该加载构造函数,并且应该初始化sessionfactory对象。

    但当我尝试: bl.instance.sessionfactory.opensession(); 我得到一个空引用异常,我看到sessionfactory为空…

    为什么?

    1 回复  |  直到 15 年前
        1
  •  3
  •   Mark Byers    15 年前

    这不是一个单子。你应该参考乔恩·斯凯特的优秀指南 singletons in C# . 例如,使用此模式:

    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;
            }
        }
    }
    

    请特别注意,该实例是静态的。