2011-05-06 69 views
6

我最近從使用ISession直接轉換到包裝的ISession,工作單元類型模式。NHibernate當前會話上下文問題

我曾經使用SQL Lite(內存中)來測試它。我有一個簡單的助手類,它配置我的SessionFactory,創建一個ISession,然後使用SchemaExport構建模式,然後返回我的ISession,並且模式一直存在,直到我關閉會話。我已經稍微改變了這一點,現在我配置一個SessionFactory,創建一個ISession,構建模式,並將工廠傳遞給我的NHibernateUnitOfWork,並將其返回給我的測試。

var databaseConfiguration = 
       SQLiteConfiguration.Standard.InMemory() 
       .Raw("connection.release_mode", "on_close") 
       .Raw("hibernate.generate_statistics", "true"); 

      var config = Fluently.Configure().Database(databaseConfiguration).Mappings(
       m => 
       { 
        foreach (var assembly in assemblies) 
        { 
         m.FluentMappings.AddFromAssembly(assembly); 
         m.HbmMappings.AddFromAssembly(assembly); 
        } 
       }); 

      Configuration localConfig = null; 
      config.ExposeConfiguration(x => 
       { 
        x.SetProperty("current_session_context_class", "thread_static"); // typeof(UnitTestCurrentSessionContext).FullName); 
        localConfig = x; 
       }); 

      var factory = config.BuildSessionFactory(); 
      ISession session = null; 

      if (openSessionFunction != null) 
      { 
       session = openSessionFunction(factory); 
      } 

      new SchemaExport(localConfig).Execute(false, true, false, session.Connection, null); 

      UnitTestCurrentSessionContext.SetSession(session); 

      var unitOfWork = new NHibernateUnitOfWork(factory, new NHibernateUTCDateTimeInterceptor()); 
      return unitOfWork; 

內部,NHibernateUnitOfWork需要得到其用於創建架構或內存數據庫實際上不會有一個模式的ISession的,所以這是它調用獲得的ISession的方法。

private ISession GetCurrentOrNewSession() 
     { 
      if (this.currentSession != null) 
      { 
       return this.currentSession; 
      } 

      lock (this) 
      { 
       if (this.currentSession == null) 
       { 
        // get an existing session if there is one, otherwise create one 
        ISession session; 
        try 
        { 
         session = this.sessionFactory.GetCurrentSession(); 
        } 
        catch (Exception ex) 
        { 
         Debug.Write(ex.Message); 
         session = this.sessionFactory.OpenSession(this.dateTimeInterceptor); 
        } 

        this.currentSession = session; 
        this.currentSession.FlushMode = FlushMode.Never; 
       } 
      } 

的問題是,this.sessionFactory.GetCurrentSession總是拋出一個異常說,ICurrentSessionContext未註冊。

我試過不同的方式來設置屬性和不同的值(正如你可以看到上面,「thread_static」和我自己的ICurrentSessionContext)但似乎沒有工作負載。

任何人有任何意見

回答

14

試試這個:

try 
{ 
    if (NHibernate.Context.CurrentSessionContext.HasBind(sessionFactory)) 
    { 
     session = sessionFactory.GetCurrentSession(); 
    } 
    else 
    { 
     session = sessionFactory.OpenSession(this.dateTimeInterceptor); 
     NHibernate.Context.CurrentSessionContext.Bind(session); 
    } 
} 
catch (Exception ex) 
{ 
    Debug.Write(ex.Message); 
    throw; 
} 
+0

這似乎已經奏效,我會適當地確認在今天晚些時候和接受。謝謝 – BenCr 2011-05-09 09:43:56

+1

您在'if'語句末尾缺少括號。 – CyberMonk 2011-09-28 19:50:10