引子
书接上文,上次我说到Mvc3开发环境的搭建,及MVC3程序的运行原理,这次着重讨论一下,MVC3+Spring.net框架的整合应用,Spring.net作为一套成熟的企业级应用框架,一直很爱开发者的喜爱。Spring.net不仅可以应用于传统的WebForm程序,在MVC程序中也有着举足轻重的地位。
添加Spring引用
Common.Logging、Spring.Core、Spring.Web,Spring.Web.Mvc
修改web.config

<configSections> <sectionGroup name="spring"> <section name="context" type="Spring.Context.Support.MvcContextHandler, Spring.Web.Mvc"/> </sectionGroup> </configSections> <spring> <context> <resource uri="~/Config/Controller.xml"/> </context> </spring> <system.web> <httpModules> <add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> <add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> <!--很重要--> <add name="Spring" type="Spring.Context.Support.WebSupportModule, Spring.Web" /> </httpModules> </system.web>
用Spring配置Controller文件

<?xml version="1.0" encoding="utf-8" ?> <objects xmlns="http://www.springframework.net"> <object id="Home" type="SpringMvcApplication1.Controllers.HomeController, SpringMvcApplication1" singleton="false"> <property name="Content" value="Spring.NET1.3.1的ASP.NET MVC依赖注入"/> </object> </objects>
注册SpringControllerFactory
ControllerBuilder.Current.SetControllerFactory(typeof(SpringControllerFactory));
在Global.asax文件中重新注册Controller对象工厂,让Spring代替MVC来管理Controller对象。不要采用spring.net官方的SpringMvcApplication类,这个类中包含很多原本global.ascx.cs中的代码,如果让global.ascx.cs继承SpringMvcApplication类,那么还需要调整global.ascx.cs类中的代码,防止与父类代码重复和冲突,实际上要在Controller中使用spring进行IoC,只需要注册ControllerFactory的实现类为SpringControllerFactory就可以了。
见证奇迹的时刻
结语
教程虽然仅仅是第一篇入门文章, 但是不是觉得已经会用Spring配置管理ASP.NET MVC了?在后续文章中,我将对Spring管理MVC的各种细节,MVC异常处理过滤器的应用.希望大家喜欢本系列文章!