没有绑定到当前上下文的会话

本文关键字:上下文 会话 绑定 | 更新日期: 2023-09-27 18:08:46

我遵循这个教程: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行:public virtual T Get(int id)第115行:{第116行:return _sessionFactory.GetCurrentSession().Get(id);第117行:118行:

当我调试它的时候,_sessionFactory不是空的,它似乎就是找不到绑定的会话。

我有httpmodule连接在我的web。配置,它确实运行,所以这不是问题。

在我的nhibernate配置中,我尝试了两个:

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

.CurrentSessionContext<CallSessionContext>()

没有绑定到当前上下文的会话

听起来您没有将会话绑定到上下文。请看下面的例子:

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

上面的关键是,无论何时检索您的第一个会话,您都将其绑定到您正在使用的任何上下文。