没有会话绑定到当前上下文
我遵循了这个教程: 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() .Mappings(m => m.FluentMappings .AddFromAssemblyOf()) .ExposeConfiguration(cfg => new SchemaExport(cfg) .Create(false, false)) .BuildSessionFactory(); }
实际错误在我的Repository.cs文件中:
第114行:公共虚拟T Get(int id)第115行:{第116行:return _sessionFactory.GetCurrentSession()。Get(id); 第117行:}第118行:
当我调试它时,_sessionFactory不是null或者任何东西,它似乎无法找到绑定的会话。
我在我的web.config中连接了httpmodule,它确实运行,所以这不是问题。
在我的nhibernate配置中,我尝试了两种方法:
.ExposeConfiguration(c => c.SetProperty("current_session_context_class", "web"))
和
.CurrentSessionContext()
但那没用。
听起来您没有将会话绑定到上下文。 请看下面的示例:
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(); } }
上面的关键是每当你检索第一个会话时,你将它绑定到你正在使用的任何上下文。