Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NHibernate Session and Transaction management in HttpModule

I've seen many implementations on the web of people managing their NHibernate sessions and transactions in a HttpModule.

The HttpModule:

  1. creates a session at the start of the request
  2. wraps the whole request in a transaction
  3. commits the transaction at the end of the request

If people use this strategy how are they handling the following scenario:

  1. request comes in
  2. retrieve object from database
  3. update object
  4. object fails validation
  5. changes to the object are still persisted because the transaction is committed in the HttpModule.

It seems that there is no good way to rollback the transaction in the above scenario. The only plan I can come up with is to:

  1. write my validation in such a way as it's guaranteed to succeed before updating my domain object (takes my validation out of my domain model).
  2. manage my transaction closer to my business logic and throw away the idea of doing it transparently in a HttpModule. (I've seen quite a few posts recommend this)

Seeing as so many people seem to be using the HttpModule approach I'm hoping there is a third way of managing this scenario that I haven't thought of?

like image 408
Brownie Avatar asked Sep 18 '10 00:09

Brownie


1 Answers

You can use some kind of global exception handling. Now I am using System.AppDomain.CurrentDomain.UnhandledException. In this handler you will need to call Transaction.Rollback(); And also condsider setting some flag (that also lives during current request only) that will point wehether you need to commit your transaction or roll back. This can make code more clear.

Edit Alternativly you can use Error event of the HttpApplication

public class HelloWorldModule : IHttpModule
{
    void Init(HttpApplication application)
    {
        application.BeginRequest += 
            (new EventHandler(this.Application_BeginRequest));
        application.EndRequest += 
            (new EventHandler(this.Application_EndRequest));
        //this is it
        applicaiton.Error +=
            (new EventHandler(this.Application_Error));
    }
like image 162
Restuta Avatar answered Oct 14 '22 07:10

Restuta