Spring.Net
简单来说,Spring是一个轻量级的控制反转(IoC)和面向切面(AOP)的容器框架。
1.创建一个空MVC项目,命名为Spring.Net.Demo
2.右键项目中的引用,选择“管理NuGet工具包”,输入“Spring.Net”,如下图

3.添加IUserInfo接口:
public interface IUserInfo { string ShowMeg(); }
4.添加Order类和UserInfo类,UserInfo类继承IUserInfo接口
public interface IUserInfo { string ShowMeg(); } public class UserInfo : IUserInfo { public string UserName { get; set; } public Order Order { get; set; } public string ShowMeg() { return UserName + "的订单号是:" + Order.OrderNo; } } public class Order { public string OrderNo { get; set; } }
5.在Web.config中添加Spring.Net配置信息
<configSections>
<!--跟下面Spring.Net节点配置是一一对应关系-->
<sectionGroup name="spring">
<section name="context" type="Spring.Context.Support.ContextHandler, Spring.Core"/>
<section name="objects" type="Spring.Context.Support.DefaultSectionHandler, Spring.Core" />
</sectionGroup>
</configSections>
<!--Spring.Net节点配置-->
<spring>
<!--容器配置-->
<context>
<resource uri="config://spring/objects"/>
</context>
<objects xmlns="http://www.springframework.net">
<!--name 必须要唯一的,type=类的全名称,所在的程序集-->
<object name="UserInfo" type="Spring.Net.Demo.UserInfo,Spring.Net.Demo">
<property name="UserName" value="神刀张三"/>
<!--ref指向下面的属性注入-->
<property name="Order" ref="Order"/>
</object>
<!--复杂属性注入-->
<object name="Order" type="Spring.Net.Demo.Order, Spring.Net.Demo">
<property name="OrderNO" value="201606122226"/>
</object>
</objects>
</spring>
6.添加Home控制器和Index视图
HomeController:
using Spring.Context; using Spring.Context.Support; using System.Web.Mvc; namespace Spring.Net.Demo.Controllers { public class HomeController : Controller { // GET: Home public ActionResult Index() { IApplicationContext context = ContextRegistry.GetContext(); IUserInfo userInfo = (IUserInfo)context.GetObject("UserInfo"); ViewBag.Msg = userInfo.ShowMeg(); return View(); } } }
Index:
@{ ViewBag.Title = "Index"; } <h2>@ViewBag.Msg</h2>
7.运行结果


浙公网安备 33010602011771号