views:

2007

answers:

2

Hi,

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

A: 

I've not used structure map but maybee I can still help guide you in the right direction. Fluent nHibernate is awsome good choice over the hbm files.

As for the http request, you do not need to ensure that you close the session when the http request ends. If you don't you'll end up leaking nHibernate session. I'm not sure if structure map will handle this for you, what I've done is I have an http module which closes the session.

One thing to note though that bite me, is that you will make to sure you wrap all your data access in a transaction and ensure nHibernate actually commits its changes. If you do this as part of your session close, you could miss the chance to handle errors. I'm curious to hear what you ended up having to do to get this workign.

JoshBerke
+4  A: 

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.

brendanjerwin
The above link is broken , it should be http://brendanjerwin.github.com/development/dotnet/2009/03/11/using-nhibernate-validator-with-fluent-nhibernate.html
Dinesh Manne
Thanks, I fixed the link in the answer.
brendanjerwin