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

与NHibernate一起处理启动问题全球.asax

  •  1
  • Fenton  · 技术社区  · 14 年前

    在我的全球.asax我在应用程序启动时配置NHibernate。这意味着我只需为我的WCF服务执行一次设置所有映射的昂贵任务。

    唯一的问题是,如果数据库在启动期间不可用,映射将永远无法设置(因为在应用程序启动期间无法设置映射,并且在应用程序池被回收之前不会再次调用事件)。

    如何处理NHibernate设置,使其只发生一次,除非出现错误(例如数据库不可用),在这种情况下,它将在每个请求上发生,直到它工作为止?

    2 回复  |  直到 14 年前
        1
  •  0
  •   Community CDub    8 年前

    你需要的是一个懒惰的单身汉来做你的会话工厂。调用一个方法来获取会话工厂,它检查会话是否已经存在。 因此,创建会话工厂的昂贵任务是在第一次有人需要时完成的 .

    你可以这样做:

    public ISessionFactory GetSessionFactory()
        {
            // sessionFactory is STATIC
            if (sessionFactory == null)
            {
    
                global::NHibernate.Cfg.Configuration cfg = new NHibernateConfigurationFactory(CurrentConfiguration).GetConfiguration(sessionFactoryName);
    
                //  Now that we have our Configuration object, create a new SessionFactory
                sessionFactory = cfg.BuildSessionFactory();
    
                if (sessionFactory == null)
                {
                    throw new InvalidOperationException("cfg.BuildSessionFactory() returned null.");
                }
            }
    
            return sessionFactory;
        }
    

    这里提供完整的解决方案:

    NHibernate - good complete working Helper class for managing SessionFactory/Session

        2
  •  0
  •   Fenton    14 年前

    使用Begin\u Request事件,而不是使用Application\u Start事件。将NHibernate会话存储在一个字段中,在Begin\u Request事件中,检查该字段是否为null,如果为null,则创建NHibernate会话(否则,继续使用已经创建的会话)。

    因此本质上,这意味着将create逻辑移到一个方法中,在“检测到会话尚未创建”的情况下,我可以从Begin\u请求调用该方法。