NHibernate session management in ASP.NET MVC

Kevin Pang picture Kevin Pang · Dec 13, 2008 · Viewed 18k times · Source

I am currently playing around with the HybridSessionBuilder class found on Jeffrey Palermo's blog post:

http://jeffreypalermo.com/blog/use-this-nhibernate-wrapper-to-keep-your-repository-classes-simple/

Using this class, my repository looks like this:

public class UserRepository : IUserRepository
{
    private readonly ISessionBuilder _sessionBuilder;

    public UserRepository(ISessionBuilder sessionBuilder)
    {
        _sessionBuilder = sessionBuilder;
    }

    public User GetByID(string userID)
    {
        using (ISession session = _sessionBuilder.GetSession())
        {
            return session.Get<User>(userID);
        }
    }
}

Is this the best way to go about managing the NHibernate session / factory? I've heard things about Unit of Work and creating a session per web request and flushing it at the end. From what I can tell, my current implementation isn't doing any of this. It is basically relying on the Repository to grab the session from the session factory and use it to run the queries.

Are there any pitfalls to doing database access this way?

Answer

Jamie Ide picture Jamie Ide · Dec 16, 2008

You should not wrap your ISession in a using statement -- the point of passing the ISessionBuilder into the repository constructor (dependency injection) is that the calling code is responsible for controlling the life cycle of the ISession. By wrapping it in a using, Dispose() is called on the ISession and you won't be able to lazy load object members or persist it.

We do something similar by just passing in an ISession to the repository constructor. Mr. Palermo's code, as I understand it, simply adds lazy initialization of the ISession. I don't think that's needed because why would you new up a repository if you're not going to use it?