VS2015ASP.NET MVC5项目中Spring.NET配置方法(超详细)

首先,在ASP.NET MVC5项目右键,如下图所示,选择“管理Nuget程序包。。。”

然后,在弹出的页面的搜索框中输入“spring.web”,在返回结果中选择Spring.Web和Spring.Web.MVC5以及Spring.Core,等待安装

 

至此,基本的Spring.Net环境所需要的外部程序已经安装完成.

 然后,接下来我们配置mvc项目的web.config文件,配置完成的截图如下:

代码如下:

<configuration>
  <configSections>

    <!-- Entity Framework configuration -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
    
    <!--log4net的块配置-->
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
    <!--Spring.Net块配置-->
    <sectionGroup name="spring">
      <section name="context" type="Spring.Context.Support.MvcContextHandler, Spring.Web.Mvc5" />
    </sectionGroup>
  </configSections>
  <!--Spring.Net的容器的配置节点-->
  <spring>
    <context>
      <resource uri="file://~/Config/common.xml" />
      <resource uri="file://~/Config/service.xml" />
      <resource uri="file://~/Config/controllers.xml" />
    </context>
  </spring>

接下来,为大家介绍Spring.Net的功能的使用(依赖注入,构建类的时候赋予属性)。比如我在Controler中想使用BLL层的一个类中的方法。那么可以如下面所示

控制器:UserInfoController

BLL层类:IUserInfoService

首先,在控制器中定义一个属性。

其次,在配置文件中,添加控制器层对应的controller.xml文件,文件路径在web.config中已经声明

<?xml version="1.0" encoding="utf-8" ?>
<objects xmlns="http://www.springframework.net">

  <object type="UI.Controllers.UserInfoController, UI" singleton="false" >
    <property name="u" ref ="UserInfoService" />
  </object>

  <object type="UI.Controllers.LoginController, UI" singleton="false" >
    <property name="UserInfoService" ref ="UserInfoService" />
  </object>

</objects>
  <object type="UI.Controllers.UserInfoController, UI" singleton="false" >
    <property name="u" ref ="UserInfoService" />
  </object>

 这段的意思是在这个控制器下的“u”这个字段的赋值是由UserInfoService配置,对应的service.xml文件如下配置:

<?xml version="1.0" encoding="utf-8" ?>
<objects xmlns="http://www.springframework.net">

  <object name="UserInfoService" type="BLL.UserInfoService, BLL" singleton="false" >
  </object>

</objects>

这样就可以做到赋值了。然后比较重要的一步是在程序开始前进行赋值,具体的操作是在Global.asax文件中:

public class MvcApplication : SpringMvcApplication

让MvcApplication来继承SpringMvcApplication这个类,

通过查看源码我们知道这个类也是继承与我们asp.net中最重要的类HttpApplication。

VS这个软件真的越来越强大了,省去了我们许多去寻找各种dll的时间。以上各个过程都是实际项目中一个小测试用的,经测试可以调用BLL层中的方法

,如果大家有什么不理解或者出现问题的地方,欢迎讨论。或者加我qq:1224327326,备注spring.net

 

posted @ 2018-11-16 17:00  王银行  阅读(2477)  评论(0编辑  收藏  举报