【问题标题】:No session bound to the current context没有会话绑定到当前上下文
【发布时间】:2011-09-18 21:32:38
【问题描述】:

我遵循了这个教程: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 行:公共虚拟 T Get(int id) 第 115 行:{ 第 116 行:返回 _sessionFactory.GetCurrentSession().Get(id); 第 117 行:} 第 118 行:

当我调试它时,_sessionFactory 不是 null 或任何东西,它似乎无法找到绑定的会话。

我在 web.config 中连接了 httpmodule,它确实可以运行,所以这不是问题。

在我的休眠配置中,我都尝试了:

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

.CurrentSessionContext<CallSessionContext>()

但这没有用。

【问题讨论】:

  • 当您说“在我的 nhibernate 配置中,我都尝试了:”时,您给出的示例都是相同的。您能否编辑您的问题以提供您尝试过的其他配置! ^^
  • 还尝试在CurrentSession()Bind( 方法中设置断点,以确保它们被调用。

标签: c# asp.net-mvc nhibernate fluent-nhibernate


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-24
    • 1970-01-01
    • 1970-01-01
    • 2014-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-19
    相关资源
    最近更新 更多