Need help with Hibernate? Read this first:
http://www.hibernate.org/ForumMailingli ... AskForHelp
Hibernate version: NHibernate 1.0.2
I am new to NHibernate, but have *some* experience with using Hibernate 3 in Java. As I read the many posts on session management for NHibernate, I began to adopt the HttpModule approach for a "session per request" pattern implementation.
I noticed that in the Java implementation using a filter, a transaction was "started" along with the session obtained. That way, the transaction logic did not have to be embedded within the service layer or within the DAOs themselves.
Here is what I have so far, based on the HttpModule posted by Ed Courtenay:
Code:
public class NHibernateHttpModule : IHttpModule {
private static readonly string SESSION_KEY = "NHibernateSession";
private static readonly string TRANSACTION_KEY = "NHibernateTransaction";
public void Init( HttpApplication context ) {
context.EndRequest += new EventHandler( context_EndRequest );
}
public void Dispose( ) { }
private void context_BeginRequest( object sender,
EventArgs e ) {
HttpApplication application = ( HttpApplication )sender;
HttpContext context = application.Context;
ISession session = NHibernateHelper.OpenSession( );
context.Items[SESSION_KEY] = session;
ITransaction transaction = session.BeginTransaction( );
context.Items[ TRANSACTION_KEY ] = transaction;
}
private void context_EndRequest( object sender, EventArgs e ) {
HttpApplication application = ( HttpApplication )sender;
HttpContext context = application.Context;
ISession session = context.Items[SESSION_KEY] as ISession;
ITransaction transaction = context.Items[ TRANSACTION_KEY ] as ITransaction;
if ( transaction != null ) {
try {
transaction.Commit( );
} catch ( Exception ) {
transaction.Rollback();
throw;
}
}
if ( session != null ) {
try {
session.Flush( );
session.Close( );
} catch { }
}
context.Items[SESSION_KEY] = null;
context.Items[TRANSACTION_KEY] = null;
}
public static ISession CurrentSession {
get {
HttpContext currentContext = HttpContext.Current;
ISession session = currentContext.Items[SESSION_KEY] as ISession;
if ( session == null ) {
session = NHibernateHelper.OpenSession( );
currentContext.Items[SESSION_KEY] = session;
ITransaction transaction = session.BeginTransaction( );
currentContext.Items[TRANSACTION_KEY] = transaction;
}
return session;
}
}
}
Any idea why this approach would not work?
Code:
`