[Update 6/11/08 - To see an example of this in action, read the introduction of S#arp Architecture.]
I've been quiet lately as I've been a very busy bee preparing the inner workings of the sequel to my NHibernate Best Practices article. In the next installment, I'll be discussing in detail how to leverage the best of Spring.NET for dependency injection and transaction management, the best of NHibernate for a nearly touch-free data access layer and non-intrusive custom collections, and ASP.NET MVC with the MvcContrib project for a bomber presentation tier.
The biggest challenge I've faced in one sitting is getting NHibernate lazy loading to work in symbiosis with Spring.NET dependency injection for controllers. The key is to leverage Spring's WebApplicationContext instead of trying to create and configure your own within Application_Start in Global.asax.cs. The steps to realize this are as follows:
-
Configure Spring.NET as you normally would for an ASP.NET application, but leave out the PageHandlerFactory setting.
-
Configure Spring.NET for your controllers. In the sample below, a data access object is being passed using constructor injection to the controller.
-
Instruct Global.asax.cs to leverage the loaded Spring.NET context when initializing the MvcContrib project's Spring.NET IoC controller factory. The crux of the problem here is that you can't get a handle on the web application context in Application_Start as it's only available after all of the HttpModules (e.g., Spring.NET's WebSupportModule) have been loaded into memory. Therefore, you must wait until HttpApplication.Init() to get a hold of the context loaded via the web.config file. The following code, which leverages MvcContrib's Spring.NET controller factory, demonstrates how to do this.
With the above in place, you can now leverage Spring.NET's dependency injection, transaction management, and the open-session-in-view pattern for NHibernate session management and lazy loading within your views. There are obviously details left out, but if you've been working on this problem, this is the concise solution. (This post uses Spring.NET 1.1, NHibernate 1.2, ASP.NET MVC Preview 2, and MvcContrib 0.0.1.96 Beta)
Billy McCafferty