众所周知,Spring在java中是很常见的框架,Spring.Net虽然体积比较大,可是功能相对齐全,本文介绍在VS2017 .Net FrameWork 4.6.1环境下,如何快速使用Spring.Net的IOC功能。话很少说,开撸Demo!java
1 准备工做git
1.1新建解决方案文件夹,新建BLL、IBLL类库项目:github
1.2 在IBLL层中添加测试接口ITest.csweb
public interface ITest { string GetName(); int GetAge(); }
1.3 在BLL层中添加具体的实现类TestBll并继承1.2中接口:spring
public class TestBll: ITest { public string GetName() { return "Test"; } public int GetAge() { return 12; } }
1.4 添加WebTest 项目,并添加相应的测试Controller:框架
2 引入Spring.Net所需Nuget包测试
2.1 在WebTest中添加Nuget包:spa
2.2 在Web.Config文件中配置Spring.Net节点:.net
<configuration> <configSections> <sectionGroup name="spring"> <section name="context" type="Spring.Context.Support.ContextHandler,Spring.Core" /> </sectionGroup> </configSections> <!--Spring.Net节点配置--> <spring> <!--容器配置--> <context> <resource uri="file://~/Config/controller.xml" /> <resource uri="file://~/Config/service.xml" /> </context> </spring>
2.3 在WebTest目录下新建Config文件夹并新建controller.xml和service.xml文件,配置以下:code
2.3.1 controller.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 type="WebTest.Controllers.SpringDoNetTestController,WebTest" singleton="false"> <property name="itest" ref="TestService"></property> </object> </objects>
2.3.2 service.xml
<?xml version="1.0" encoding="utf-8" ?> <objects> <object name="TestService" type="BLL.TestBll,BLL"> </object> </objects>
这两个文件在Web.Config文件中已经被添加,记得controller文件要放在上面。
2.4 让Spring.Net接管MVCApplication:
在global文件中作以下调整:
3 测试
3.1 Controller文件中添加以下代码,记得添加相应的Index视图:
public class SpringDoNetTestController : Controller { public ITest itest { get; set; } // GET: SpringDoNetTest public ActionResult Index() { var name = itest.GetName(); return View(name); } }
3.2 打断点测试
4 可能出现的状况
4.1 未能加载文件或程序集“System.Web.Http, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35”或它的某一个依赖项。系统找不到指定的文件。
解决方法:Nuget安装或更新Microsoft.AspNet.WebApi,
安装命令:Install-Package Microsoft.AspNet.WebApi
更新命令:Update-Package Microsoft.AspNet.WebApi
4.2 Could not load type from string value 'BLL.TestBll,BLL'.
解决方法:引用BLL以及IBLL
5 后记
本篇Demo在GitHub能够下载,下载地址为:https://github.com/WangBank/SpringDoNetForVS2017
这篇文章是关于Spring.Net中IOC功能的简单实用,之后会逐渐更新其AOp功能以及其余IOC框架,譬如Unity、AutoFac等等,但愿你们能够支持。