I followed this tutorial: http://nhforge.org/blogs/nhibernate/archive/2011/03/03/effective-nhibernate-session-management-for-web-apps.aspx
I am not getting a 'no session bound to the current context' error when trying to load a page (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();
}
The actual error is in my Repository.cs file:
Line 114: public virtual T Get(int id) Line 115: { Line 116: return _sessionFactory.GetCurrentSession().Get(id); Line 117: } Line 118:
When I was debugging it, _sessionFactory wasn't null or anything, it just can't seem to find the bound session.
I have the httpmodule wired up in my web.config, and it does get run so that's not the problem.
In my nhibernate configuration, I tried both:
.ExposeConfiguration(c => c.SetProperty("current_session_context_class", "web"))
and
.CurrentSessionContext<CallSessionContext>()
But that didn't work.
It sounds like you are not binding your session to the context. Look at the below for an example:
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();
}
}
The key to the above is that whenever you retrieve your first session you bind it to whatever context you are using.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With