Images in this post missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at imagehelp@codebetter.com
Using Spring.NET and NHibernate with ASP.NET MVC

[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:

  1. Configure Spring.NET as you normally would for an ASP.NET application, but leave out the PageHandlerFactory setting.
    <?xml version="1.0" encoding="utf-8"?> <configuration> <configSections> <sectionGroup name="spring"> <section name="context" type="Spring.Context.Support.WebContextHandler, Spring.Web"> ... </sectionGroup> </configSections> ... <spring> <context> <resource uri="~/SpringConfig/Spring.xml"> </context> </spring> <system.web> <httpModules> <add name="OpenSessionInView" type="Spring.Data.NHibernate.Support.OpenSessionInViewModule, Spring.Data.NHibernate12"> <add name="Spring" type="Spring.Context.Support.WebSupportModule, Spring.Web"> ... </httpModules> </system.web> </configuration>
  2. Configure Spring.NET for your controllers.  In the sample below, a data access object is being passed using constructor injection to the controller.
    <?xml version="1.0" encoding="utf-8"?> <objects xmlns="http://www.springframework.net"> <description> MVC Controller declarations. </description> <object id="HomeController" type="Northwind.Controllers.HomeController, Northwind.Controllers"> <object id="CustomersController" type="Northwind.Controllers.CustomersController, Northwind.Controllers"> <constructor-arg ref="CustomerDao"> </object> </objects>
  3. 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.
    public class GlobalApplication : System.Web.HttpApplication { protected void Application_Start(object sender, EventArgs e) { RegisterRoutes(RouteTable.Routes); } public void RegisterRoutes(RouteCollection routes) { ... } public override void Init() { base.Init(); ConfigureIoC(); } private void ConfigureIoC() { WebApplicationContext webApplicationContext = ContextRegistry.GetContext() as WebApplicationContext; DependencyResolver.InitializeWith( new SpringDependencyResolver(webApplicationContext.ObjectFactory)); ControllerBuilder.Current.SetControllerFactory(typeof(IoCControllerFactory)); } }

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


Posted 04-04-2008 4:38 PM by Billy McCafferty

[Advertisement]

Comments

Steve Gentile wrote re: Using Spring.NET and NHibernate with ASP.NET MVC
on 04-04-2008 8:26 PM

Interesting topic - I spent half my day today building a Northwind sample that uses the spring.net 1.1, nhibernate 1.2.1 and MS MVC  :)

I'm injecting the Dao into the controller as well  :)

Spring.NET  + NHibernate is a great setup!

I'd like to figure out how to use the new NHibernate 2.0 with Ayende's NHibernate over Linq, but I'm concerned the spring wouldn't handle it.

Billy McCafferty wrote re: Using Spring.NET and NHibernate with ASP.NET MVC
on 04-04-2008 8:44 PM

My thoughts exactly!

Vlad Navazhylau wrote re: Using Spring.NET and NHibernate with ASP.NET MVC
on 04-05-2008 3:29 PM

Can't wait for full article! Thanks!

Links Today (2008-04-06) wrote Links Today (2008-04-06)
on 04-06-2008 11:33 AM

Pingback from  Links Today (2008-04-06)

Reflective Perspective - Chris Alcock » The Morning Brew #67 wrote Reflective Perspective - Chris Alcock &raquo; The Morning Brew #67
on 04-07-2008 3:07 AM

Pingback from  Reflective Perspective - Chris Alcock  &raquo; The Morning Brew #67

Dew Drop - April 7, 2008 | Alvin Ashcraft's Morning Dew wrote Dew Drop - April 7, 2008 | Alvin Ashcraft's Morning Dew
on 04-07-2008 8:03 AM

Pingback from  Dew Drop - April 7, 2008 | Alvin Ashcraft's Morning Dew

DotNetKicks.com wrote Using Spring.NET and NHibernate with ASP.NET MVC
on 04-08-2008 10:38 AM

You've been kicked (a good thing) - Trackback from DotNetKicks.com

Nick wrote re: Using Spring.NET and NHibernate with ASP.NET MVC
on 04-08-2008 7:06 PM

Regarding Linq to NHibernate, this is just a query layer on top of NH - you can go ahead and integrate NH the normal way.

Your repositories may expose or use an IQueryable<T>, and things will just work as usual.

Not 100% sure about building Linq to NH with NH 2.0, but I'd say its possible.

Nick

Mark Pollack wrote re: Using Spring.NET and NHibernate with ASP.NET MVC
on 04-09-2008 10:28 AM

Hi Billy,

I've always enjoyed your articles and I'm certainly looking forward to this one.  Let me know if there is anything I can do to be of help.

Note that an open issue is to provide separate exception translation advice to convert NHibernate exceptions to Spring's DAO exception hierarchy. This way you can get all the benefits of HibernateTemplate but using the standard NHibernate API.  This already exists in Spring.Java, some details are here - blog.springsource.com/.../so-should-you-still-use-springs-hibernatetemplate-andor-jpatemplate

Cheers,

Mark Pollack (Spring.NET guy... ;)

Wöchentliche Rundablage: Silverlight 2, ASP.NET MVC, .NET 3.5, jQuery, CSS, Powershell | Code-Inside Blog wrote W&ouml;chentliche Rundablage: Silverlight 2, ASP.NET MVC, .NET 3.5, jQuery, CSS, Powershell | Code-Inside Blog
on 04-14-2008 8:30 AM

Pingback from  W&ouml;chentliche Rundablage: Silverlight 2, ASP.NET MVC, .NET 3.5, jQuery, CSS, Powershell | Code-Inside Blog

Weekly Links: Silverlight 2, ASP.NET MVC, .NET 3.5, jQuery, CSS, Powershell | Code-Inside Blog International wrote Weekly Links: Silverlight 2, ASP.NET MVC, .NET 3.5, jQuery, CSS, Powershell | Code-Inside Blog International
on 04-14-2008 8:39 AM

Pingback from  Weekly Links: Silverlight 2, ASP.NET MVC, .NET 3.5, jQuery, CSS, Powershell | Code-Inside Blog International

Jmosco wrote re: Using Spring.NET and NHibernate with ASP.NET MVC
on 04-17-2008 6:32 PM

Do you have the project in a zip file?

this instructions works in VS 2003?

Thanks

Billy McCafferty wrote re: Using Spring.NET and NHibernate with ASP.NET MVC
on 04-17-2008 8:16 PM

Honestly, I'm not sure if this will work in VS 2003...I don't think it will.  I *believe* that it's dependent on .NET 2.0, but it *may* work with .NET 1.1...not sure though.  My example project definitely wouldn't work in VS 2003 though...you'd have to upgrade to VS 2008.

jmosco wrote re: Using Spring.NET and NHibernate with ASP.NET MVC
on 05-13-2008 9:26 AM

Hi Billy, i implemeted Spring .Net and NHibernate in VS 2003 but i can use Hibernate Template, do you have some suggestions for this.

I like how it works, but i would like work with NHibernate template.

See you.

ravelo wrote re: Using Spring.NET and NHibernate with ASP.NET MVC
on 05-14-2008 4:26 AM

Hi Billy, I've used a Nhibernet with spring.Net, on the test an exception was standing, and an error message was dispalaying as "class unkwon" .

Could you give me a solution please

Billy McCafferty wrote re: Using Spring.NET and NHibernate with ASP.NET MVC
on 05-15-2008 12:34 PM

Make sure that the HBM is compiled as an "Embedded Resource" in its properties.

Billy McCafferty wrote re: Using Spring.NET and NHibernate with ASP.NET MVC
on 05-15-2008 12:42 PM

@jmosco,

I'll be posting a fully working sample later today.

Cialis best price buy online. wrote Online pharmacy buy cialis.
on 07-16-2008 10:41 PM

Cialis online. Cialis best price buy online.

ASP.NET MVC Archived Buzz, Page 1 wrote ASP.NET MVC Archived Buzz, Page 1
on 07-28-2008 4:39 PM

Pingback from  ASP.NET MVC Archived Buzz, Page 1

ASP Net Web Development wrote re: Using Spring.NET and NHibernate with ASP.NET MVC
on 09-01-2008 8:05 AM

Ver few articles are available on using Spring.NET and NHibernate with ASP.NET MVC... great explanation thank you...

Casino wrote re: Using Spring.NET and NHibernate with ASP.NET MVC
on 09-23-2008 3:57 PM

The New Dress summary and study guide, with notes, essays, quotes, and pictures.

Poker wrote re: Using Spring.NET and NHibernate with ASP.NET MVC
on 09-23-2008 7:41 PM

Information about cell phones for the US Detailed info on new phones, news

Casino wrote re: Using Spring.NET and NHibernate with ASP.NET MVC
on 09-23-2008 7:42 PM

The New Dress summary and study guide, with notes, essays, quotes, and pictures.

BLACKJACK wrote re: Using Spring.NET and NHibernate with ASP.NET MVC
on 09-23-2008 7:43 PM

Get the latest mobile phones online at Dialaphone, the mobile phone shop offering great deals on the latest mobile phones.

BLACKJACK wrote re: Using Spring.NET and NHibernate with ASP.NET MVC
on 09-23-2008 7:44 PM

Get the latest mobile phones online at Dialaphone, the mobile phone shop offering great deals on the latest mobile phones.

DotNetShoutout wrote Using Spring.NET and NHibernate with ASP.NET MVC
on 11-20-2008 5:04 AM

Your Story is Submitted - Trackback from DotNetShoutout

Sean Gilbert wrote ADO.NET Entity Framework with Oracle
on 11-20-2008 2:50 PM

ADO.NET Entity Framework with Oracle

grim wrote re: Using Spring.NET and NHibernate with ASP.NET MVC
on 11-25-2008 9:52 AM

Hey, Billy. I try today use your sample but that do not work for me.

MVC IControllerFactory  have default implement and after each request they always create new instance of requested controller, in spring framework we always have singleton version. And in that case on post request we always have data witch sended in first post request

sorry for my poor english

Billy McCafferty wrote re: Using Spring.NET and NHibernate with ASP.NET MVC
on 11-25-2008 10:11 AM

Hi grim,

As you noted, each controller is created upon every request.  In the earlier versions, but you could provide your own controller factory, instead of using the one within the framework to ensure that controllers follow the singleton pattern.

grim wrote re: Using Spring.NET and NHibernate with ASP.NET MVC
on 11-25-2008 10:37 AM

Thanx for fast answer.

I work at application which using Spring.NET and yes, now  i try implement my own factory which be support that IoC framework but i cannot find object in controller class which need cleansing

my goal is make singleton controller with all DJ looks like first time created

can you help me with that?

my mail is max.itcn@gmail.com

Billy McCafferty wrote re: Using Spring.NET and NHibernate with ASP.NET MVC
on 11-25-2008 10:50 AM

If you're using Ninject, you can modify your custom controller factory to create controllers as singletons instead of being transient.  Here's a webcast concerning this capability:  dimecasts.net/.../38

Code Monkey Labs wrote Weekly Web Nuggets #7
on 02-22-2009 10:51 PM

General NCover 2.1.0 Released : The latest update to a very popular code coverage tool, now supporting .Net 3.0 &amp; 3.5! Using Entity Framework with Disconnected N-Tier Objects : Ruurd Boeke has a good post about using Entity Framework objects across

Pharmf88 wrote re: Using Spring.NET and NHibernate with ASP.NET MVC
on 05-24-2009 9:49 AM

Very nice site! <a href="apeyixo.com/.../1.html">cheap viagra</a>

Pharme198 wrote re: Using Spring.NET and NHibernate with ASP.NET MVC
on 05-24-2009 9:50 AM

Very nice site! <a href="apeyixo.com/.../1.html">cheap viagra</a>

Pharma628 wrote re: Using Spring.NET and NHibernate with ASP.NET MVC
on 05-24-2009 9:50 AM

Very nice site!  [url=apeyixo.com/.../2.html]cheap cialis[/url]

Pharme335 wrote re: Using Spring.NET and NHibernate with ASP.NET MVC
on 05-24-2009 9:51 AM

Very nice site!  [url=apeyixo.com/.../2.html]cheap cialis[/url]

Pharmc569 wrote re: Using Spring.NET and NHibernate with ASP.NET MVC
on 05-24-2009 9:51 AM

Very nice site! cheap cialis apeyixo.com/.../4.html

Pharme306 wrote re: Using Spring.NET and NHibernate with ASP.NET MVC
on 05-24-2009 9:51 AM

Very nice site! cheap cialis apeyixo.com/.../4.html

Pharmb519 wrote re: Using Spring.NET and NHibernate with ASP.NET MVC
on 05-24-2009 9:51 AM

Very nice site!

Pharmb23 wrote re: Using Spring.NET and NHibernate with ASP.NET MVC
on 05-24-2009 9:52 AM

Very nice site!

Pharmg105 wrote re: Using Spring.NET and NHibernate with ASP.NET MVC
on 06-17-2009 11:08 AM

Very nice site!

viagra sale wrote re: Using Spring.NET and NHibernate with ASP.NET MVC
on 07-20-2009 10:00 AM

kNwm89 dvonuidq kvouluqc iipybzli

online viagra wrote re: Using Spring.NET and NHibernate with ASP.NET MVC
on 07-20-2009 6:51 PM

Msmyjj vlrojjit xlufbeoq vdcrpyht

viagra wrote re: Using Spring.NET and NHibernate with ASP.NET MVC
on 07-21-2009 8:14 AM

LzOIi9 minipcrb rvilanah gzljoeqc

Pharmk432 wrote re: Using Spring.NET and NHibernate with ASP.NET MVC
on 08-02-2009 9:51 AM

Very nice site!

Pharmc534 wrote re: Using Spring.NET and NHibernate with ASP.NET MVC
on 08-13-2009 1:11 AM

Very nice site!

About The CodeBetter.Com Blog Network
CodeBetter.Com FAQ

Our Mission

Advertisers should contact Brendan

Subscribe
Google Reader or Homepage

del.icio.us CodeBetter.com Latest Items
Add to My Yahoo!
Subscribe with Bloglines
Subscribe in NewsGator Online
Subscribe with myFeedster
Add to My AOL
Furl CodeBetter.com Latest Items
Subscribe in Rojo

Member Projects
DimeCasts.Net - Derik Whittaker

Friends of Devlicio.us
Red-Gate Tools For SQL and .NET

NDepend

SlickEdit
 
SmartInspect .NET Logging
NGEDIT: ViEmu and Codekana
LiteAccounting.Com
DevExpress
Fixx
NHibernate Profiler
Unfuddle
Balsamiq Mockups
Scrumy
JetBrains - ReSharper
Umbraco
NServiceBus
RavenDb
Web Sequence Diagrams
Ducksboard<-- NEW Friend!

 



Site Copyright © 2007 CodeBetter.Com
Content Copyright Individual Bloggers

 

Community Server (Commercial Edition)