This is based on: http://nhforge.org/blogs/nhibernate/archive/2011/03/03/effective-nhibernate-session-management-for-web-apps.aspx
Code is here: https://gist.github.com/852307
My questions are, in the DAO:
//Example of dao
public class Dao<T> : IDao<T>
{
private readonly ISessionFactory sessionFactory;
public Dao(ISessionFactory sessionFactory)
{
this.sessionFactory = sessionFactory;
}
public void Save(T transient)
{
sessionFactory.GetCurrentSession().Save(transient);
}
}
I guess the ISessionFactory get’s autoatically wired up using windsor correct?
public class NHibernateInstaller : IWindsorInstaller
{
#region IWindsorInstaller Members
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container.Register(Component.For<ISessionFactory>()
.UsingFactoryMethod(k => BuildSessionFactory()));
container.Register(Component.For<NHibernateSessionModule>());
container.Register(Component.For<ISessionFactoryProvider>().AsFactory());
container.Register(Component.For<IEnumerable<ISessionFactory>>()
.UsingFactoryMethod(k => k.ResolveAll<ISessionFactory>()));
HttpContext.Current.Application[SessionFactoryProvider.Key]
= container.Resolve<ISessionFactoryProvider>();
}
#endregion
public ISessionFactory BuildSessionFactory() { ... }
}
But in the DAO, when the method is called:
sessionFactory.GetCurrentSession()
How does this snippet and the HttpModule that opens the session work?
I don’t see how GetCurrentSession() hooks into the session that was opened by the HttpModule since GetCurrentSession is a built in method?
It’s using NHibernate contextual sessions:
http://www.nhforge.org/doc/nh/en/index.html#architecture-current-session
All the magic happens in LazySessionContext. Whenever the bind method is called this saves the session in an nhibernate context. In your case the context would be LazySessionContext which is a custom context (inherits from NH’s ICurrentSessionContext) used by this application. There are 4 or 5 different types of standard contextual sessions in version 3.2 of nhibernate.
The GetCurrentSession method basically retrieves your saved (saved session in bind call) NH session from earlier.