Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using (Fluent) NHibernate with StructureMap (or any IoCC)

On my quest to learn NHibernate I have reached the next hurdle; how should I go about integrating it with StructureMap?

Although code examples are very welcome, I'm more interested in the general procedure.

What I was planning on doing was...

  • Use Fluent NHibernate to create my class mappings for use in NHibs Configuration
  • Implement ISession and ISessionFactory
  • Bootstrap an instance of my ISessionFactory into StructureMap as a singleton
  • Register ISession with StructureMap, with per-HttpRequest caching

However, don't I need to call various tidy-up methods on my session instance at the end of the HttpRequest (because thats the end of its life)?

If i do the tidy-up in Dispose(), will structuremap take care of this for me?

If not, what am I supposed to do?

Thanks

Andrew

like image 785
Andrew Bullock Avatar asked Oct 15 '22 17:10

Andrew Bullock


1 Answers

I use StructureMap with fluent-nhibernate (and NH Validator) in 3 of my current projects. 2 of those are ASP MVC apps and the third is a WCF web service.

Your general strategy sounds about right (except you won't be making your own Session or SessionFactory, as was already pointed out in comments). For details, snag my configuration code from here:

http://brendanjerwin.github.com/development/dotnet/2009/03/11/using-nhibernate-validator-with-fluent-nhibernate.html

The post is really about integrating NH Validator and Fluent-NHibernate but you can see exactly how I register the session factory and ISession with StructureMap in the "Bonus" section of the post.

RE: Tidy up: You should try and always work within a transaction and either commit or roll-back the transaction at the end of your unit of work. NH only utilizes SQL Connections when it needs them and will take care of the cleanup of that limited resource for you. Normal garbage collection will take care of your sessions themselves.

The Session Factory is a very expensive object that you will want to only initialize once and keep around for the life of your app.

like image 83
brendanjerwin Avatar answered Nov 15 '22 05:11

brendanjerwin