废话没有,直接上代码
//NHibernate构造类
  public static class NHibernateContextSessionFactory
 {
 private const string CurrentSessionKey = "nhibernate.current_session";
        private static ISessionFactory sessionFactory;       //静态构造函数
        static NHibernateContextSessionFactory()
        {
            if (sessionFactory == null)
            {
                Stopwatch sw = new Stopwatch();
                sw.Start();
                sessionFactory = new ConfigurationBuilder().Build().BuildSessionFactory();
                sw.Stop();
                Debug.WriteLine("获取session工厂耗时:" + sw.ElapsedMilliseconds + " 毫秒");
            }
        }        public static ISession GetSession()
        {
            ISession currentSession = CallContext.GetData(CurrentSessionKey) as ISession;
            if (currentSession == null)
            {
                currentSession = sessionFactory.OpenSession();
                CallContext.SetData(CurrentSessionKey, currentSession);
            }            return currentSession;
        }
}问题: 我发现 网站有时候访问特别快,但有时候就特别慢。
研究下来 发现时由于  sessionFactory = new ConfigurationBuilder().Build().BuildSessionFactory();
特别耗时间,每次BuildSessionFactory() 都会耗时1秒,而 这不是最重要的,最重要的是 他还会经常执行,奇怪的问题就在这里了 sessionFactory是个静态的对象啊,按道理讲 他只会运行一次,怎么会重复运行呢?关于 网站的架构是 UI->BLL->DAL层的 某个仓储(**Repository)->仓储中 调用的上述类中的GetSession()。
求大神指教,我自己也做了一个别的小测试,在那个测试中是没有问题的,静态构造函数 只会运行一次,但这个会重复运行

解决方案 »

  1.   


    我在这个上面 写过单例模式,但还是 会执行 也就是说 静态的_instance会为空我觉得问题不在于 用哪个模式,而在于 为什么 单例中的静态的_instance会为空
    而非单例中的 static ISessionFactory sessionFactory; 也会为空???
      

  2.   


    不明白, 程序在DAL层 进行数据库操作 都是 先到这获取 Isession
    但他是静态构造函数,而且 sessionFactory 是个静态的对象。  为什么总会运行 静态构造函数
      

  3.   

    再次贴下代码  加上部分注释 方便大家看/NHibernate构造类
      public static class NHibernateContextSessionFactory
     {
     private const string CurrentSessionKey = "nhibernate.current_session";
            private static ISessionFactory sessionFactory;//这个在程序运行中.不明白为什么会为空,他是静态的呀..
     
           //静态构造函数 这个构造函数 还会经常运行其中 sessionFactory就为NULL了
            static NHibernateContextSessionFactory()
            {
                if (sessionFactory == null)
                {
                    Stopwatch sw = new Stopwatch();
                    sw.Start();
                    sessionFactory = new ConfigurationBuilder().Build().BuildSessionFactory();
                    sw.Stop();
                    Debug.WriteLine("获取session工厂耗时:" + sw.ElapsedMilliseconds + " 毫秒");
                }
            }
     
            public static ISession GetSession()
            {
                ISession currentSession = CallContext.GetData(CurrentSessionKey) as ISession;
                if (currentSession == null)
                {
                    currentSession = sessionFactory.OpenSession();
                    CallContext.SetData(CurrentSessionKey, currentSession);
                }
     
                return currentSession;
            }
    }