Integrating Castle Windsor and NHibernate with WCF

Integrating Castle Windsor and NHibernate with WCF

Up until now, we were using the NHibernate facility of Castle Windsor for managing our NHibernate sessions in WCF. But, we want to have a session-per-request approach as one would use when integrating NHibernate with a regular web application.

Yesterday I did a small spike to figure out how this should work. It turned out to be pretty easy. I used this excellent blog post written by Oran Dennison as my guide.

I created a wrapper class around for Castle Windsor named DependencyContainer. The GetInstance method opens a new session using the SessionFactory object we instantiated in the service behavior class. The session object is then registered with Castle Windsor. We can now implement our repositories like this:

There is also another way for achieving this that I will be investigating the next week or so using the WCF Integration Facility for Castle Windsor. For some reason it is not available in the current release of the Castle stack so I have to grab it from the trunk.

If you have any thoughts, improvements or suggestions I’m glad to hear them from you, my dear reader. It’s the only way I’ll ever learn :-).

Jan,
I also use a similar approach (w/ Unity & EF). When doing some profiling the past few days I noticed that the service itself was not being disposed, even though it implements IDispoable. (I clean up the EF context there)

It appears when using the IInstanceProvider, ReleaseContext will not Dispose of the service itself. I added the following code, which seems to work well. (w/ a battery of tests, faults, exceptions etc).