Search code examples
asp.net-mvcnhibernatehttpmodule

ASP.NET MVC, NHibernate sessions, and NHibernate events


I'm using (Fluent) NHibernate in an ASP.NET MVC3 project. I'm using the standard approach of opening one NHibernate session per request by implementing a custom HttpModule. The session gets opened in BeginRequest and closed in EndRequest.

I'm hooking into the Pre/Post Insert/Update events to write a history log for my entities. The problem arises when I try to save the entity in these event handlers. It seems as though EndRequest has already been called before these event handlers, and hence the NHibernate session is already closed.

How can I delay the closing of the session so I can save the history entities? I've looked at some of the HttpModules at rhino commons, but it seems overkill for my situation.


Solution

  • You might want to check out this post by Ayende. I believe you'll find your answer in the comments made by Revin Hart. Ayende and Revin talk about getting a child session to handle saving the change log entity.

    ISession newSession = ev.Source.PersistenceContext.Session.GetSession();
    
    foreach (ScheduleChangeLog changeLog in logs)
    {
        changeLog.UpdatedBy = Username;
        newSession.Save(changeLog);
    }