IOC - DI - Spring

使用 Spring 来做依赖注入

 

首先在 Core 层配置 xml

<?xml version="1.0" encoding="utf-8" ?>
<objects xmlns="http://www.springframework.net">
  <!--用户管理-->
  <!-- id:      用于 Controller 层能找到对应的标签 -->
  <!-- type:    格式为: 命名空间.类名, 程序集 (有时候程序集就等于命名空间) -->
  <!-- singleton:    -->
  <object id="Service.User" type="WebApplication5.Core.UserCore,WebApplication5.Core" singleton="false">
  </object>
</objects>

 

之后 在 Controller 层配置 关联到 Core 的 xml

<?xml version="1.0" encoding="utf-8" ?>
<objects xmlns="http://www.springframework.net">
  <!--用户管理-->
  <!-- type: 格式为: 命名空间.类名, 程序集 (有时候程序集就等于命名空间) -->
  <!-- singleton:    -->
  <object type="WebApplication5.Controllers.UserController, WebApplication5.Controllers" singleton="false">
      <!-- name: 在 Controller 中引用的 变量名 -->
      <!-- ref:  指向 Core.xml 中的 Id -->
    <property name="userCore" ref="Service.User"/>
  </object>
</objects>

 

配置 启动项目的 Web.config

<configSections>
<sectionGroup name="spring">
  <!--Spring声明容器-->
  <section name="context" type="Spring.Context.Support.MvcContextHandler, Spring.Web.Mvc5" />
  <section name="objects" type="Spring.Context.Support.DefaultSectionHandler, Spring.Core" />
</sectionGroup>
</configSections>
<!--Spring配置指向-->
<spring>
<context>
  <!-- Controller 层 -->
  <!-- uri 格式为: assembly://程序集名/命名空间/配置文件.xml -->
  <resource uri="assembly://WebApplication5.Controllers/WebApplication5.Controllers/theController.xml" />
  <!-- Core 层 格式为: assembly://程序集名/命名空间/配置文件.xml-->
  <resource uri="assembly://WebApplication5.Core/WebApplication5.Core/theCore.xml" />
</context>
</spring>

 

在 启动项目中 引用 程序集

Spring.Core (Common.Logging, Common.Logging.Core)

Spring.Web

Spring.Web.Mvc5

 

Microsoft.AspNet.WebApi (System.Web.Http.WebHost)

Microsoft.AspNet.WebApi.Core (System.Web.Http)

 

修改启动项目的 Global.asax

继承自 Spring.Web.Mvc.SpringMvcApplication

Spring.Web.Mvc.SpringMvcApplication 继承自 HttpApplication

public class MvcApplication : Spring.Web.Mvc.SpringMvcApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        RouteConfig.RegisterRoutes(RouteTable.Routes);
    }
}

 

之后在 Controller 直接引用接口就好了

public class UserController : Controller
{
        IUserCore userCore;

        public ActionResult Index()
        {
            ViewBag.Name = userCore.GetName();
            return View();
        }
}

 

posted @ 2016-07-09 10:55  `Laimic  阅读(100)  评论(0)    收藏  举报