添加必要的引用
MVC5应用中必要的dll如下:
Common.Logging.dll
Spring.Core.dll
Spring.Web.dll
Spring.Web.Mvc5.dll
Spring.Web.Extensions.dll
安装如下Nuget包:
install-package spring.core
install-package spring.web
install-package spring.web.mvc5
install-package spring.web.extensions
配置spring.net
在MVC项目下添加Config文件夹,新增俩个xml:controllers.xml
,services.xml
如何配置?参考:http://blog.csdn.net/zhaobw831/article/details/78039380
controllers.xml:
<?xml version="1.0" encoding="utf-8" ?>
<objects xmlns="http://www.springframework.net">
<description>An example that demonstrates simple IoC features.</description>
<!--object的name可以自定义,property中的属性name不能自定义-->
<object name="" type="SpringNet.MVC.Controllers.HomeController,SpringNet.MVC" singleton="false">
<property name="test" ref="TestService"></property>
</object>
</objects>
services.xml:
<?xml version="1.0" encoding="utf-8" ?>
<objects>
<object name="TestService" type="SpringNet.Service.TestClass,SpringNet.Service">
</object>
</objects>
右键属性,将这俩个xml的输出目录改为总是输出,如下:
修改web.config
在configuration下的第一个节点添加:
<!--spring.net 配置开始-->
<configSections>
<sectionGroup name="spring">
<section name="context" type="Spring.Context.Support.MvcContextHandler, Spring.Web.Mvc5" />
</sectionGroup>
</configSections>
<spring>
<context>
<resource uri="file://~/Config/controllers.xml" />
<resource uri="file://~/Config/services.xml" />
</context>
</spring>
<!--spring.net 配置结束-->
修改Global.asax.cs的父类,添加测试代码
将System.Web.HttpApplication
改为:Spring.Web.Mvc.SpringMvcApplication
HomeController.cs:
Service.TestClass test { get; set; }
public ActionResult Test()
{
string result = test.TestGet();
return Content(result);
}
业务层下的TestClass.cs:
public class TestClass
{
public string TestGet()
{
return "this is test content";
}
}
运行程序,发现一个错误:
原因为未引用System.Web.Http
,可添加dll引用,也可以再nuget包中添加webapi引用:
install-package microsoft.aspnet.webapi
重新运行程序,成功:
源码
本文源码:Github
spring.net源码:https://github.com/spring-projects/spring-net