0

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.

3
  • Use a dedicated Session to perform these tasks, maybe? We use these events for auditing purposes also, and we perform these operations in a separate Session. Commented Jul 30, 2012 at 20:51
  • Those events occur within the transaction. You are using transactions, right? Commented Jul 31, 2012 at 1:28
  • @DiegoMijelshon Yes, everything within the request is handled in a transaction. The problem is that the request is ending before the event handlers are called. Commented Aug 3, 2012 at 13:28

1 Answer 1

1

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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect! Long story short I did have to create a new session.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.