2011-09-17 44 views
6

沒有會話我跟着這個教程:http://nhforge.org/blogs/nhibernate/archive/2011/03/03/effective-nhibernate-session-management-for-web-apps.aspx綁定到當前上下文

我沒有得到一個嘗試加載頁面時錯誤「綁定到當前上下文中沒有會話」(MVC 3)。

public static ISessionFactory BuildSessionFactory() 
     { 

      return Fluently.Configure() 
       .Database(MsSqlConfiguration.MsSql2008 // 
           .ConnectionString(@"Server=.\SQLExpress;Database=db1;Uid=dev;Pwd=123;") 
           .ShowSql()) 
       //.ExposeConfiguration(c => c.SetProperty("current_session_context_class", "web")) 
       //.CurrentSessionContext<CallSessionContext>()    
       .Mappings(m => m.FluentMappings 
            .AddFromAssemblyOf<User>()) 
       .ExposeConfiguration(cfg => new SchemaExport(cfg) 
               .Create(false, false)) 
       .BuildSessionFactory(); 
     } 

實際的錯誤是在我Repository.cs文件:

114線:公共虛擬噸得到(INT ID) 115線:{ 116線:返回_sessionFactory.GetCurrentSession()獲取(ID); 117行:} 118行:

當我調試它時,_sessionFactory不是null或任何東西,它似乎無法找到綁定的會話。

我有我的web.config連接httpmodule,它確實得到運行,所以這不是問題。

在我的NHibernate的配置,我都嘗試:

.ExposeConfiguration(c => c.SetProperty("current_session_context_class", "web")) 

.CurrentSessionContext<CallSessionContext>() 

但沒有奏效。

+1

當你說「在我的nhibernate配置中,我嘗試了兩個:」,你給的例子都是一樣的。你可以編輯你的問題給你嘗試的其他配置! ^^ –

+1

也嘗試在'CurrentSession()'和'Bind('方法,以確保它們被調用的內部設置斷點。 –

回答

8

這聽起來像你沒有把你的會話綁定到上下文。看下面的例子:

public class SessionFactory 
{ 
    protected static ISessionFactory sessionFactory; 
    private static ILog log = LogManager.GetLogger(typeof(SessionFactory)); 

    //Several functions omitted for brevity 

    public static ISession GetCurrentSession() 
    { 
     if(!CurrentSessionContext.HasBind(GetSessionFactory())) 
      CurrentSessionContext.Bind(GetSessionFactory().OpenSession()); 

     return GetSessionFactory().GetCurrentSession(); 
    } 

    public static void DisposeCurrentSession() 
    { 
     ISession currentSession = CurrentSessionContext.Unbind(GetSessionFactory()); 

     currentSession.Close(); 
     currentSession.Dispose(); 
    } 
} 

上述的關鍵是,無論何時你檢索你的第一次會議,你綁定它到任何你使用的上下文。