Monday, August 9, 2010

Use StructureMap To Create And Dispose Of NHibernate Sessions

If you are using StructureMap to manage sessions for NHibernate, you may have encountered situations where you would like to dispose of those sessions in a clean and efficient manner. You could create your own code to manage this (good luck with that) or you could use StructureMap to handle that too.

In the current version of StructureMap, you can use the following code placed in the Application_EndRequest event of your Global.asax file.

ObjectFactory.ReleaseAndDisposeAllHttpScopedObjects();

If you are using an old release of StructureMap, you can use the following code placed in the Application_EndRequest event of your Global.asax file.

HttpContextBuildPolicy.DisposeAndClearAll();

Either way, you can use StructureMap to manage the clean up of your sessions in NHibernate. I hope this knowledge makes your life easier!


Smooches,

Kila

2 comments:

Anonymous said...

Good tip :)

ck said...

I am using this code, however, disposing of the session this way does not seem to flush the session. So, I'm left with flushing it explicitly (or using a transaction and committing).

Am I missing something?