设为首页 加入收藏

TOP

接之前的文章,VS2017中使用Spring.NET配置以及使用方法(framework4.6.1超详细)
2019-09-17 18:58:29 】 浏览:29
Tags:之前 文章 VS2017 使用 Spring.NET 配置 以及 使用方法 framework4.6.1 详细

    众所周知,Spring在java中是很常见的框架,Spring.Net虽然体积比较大,但是功能相对齐全,本文介绍在VS2017 .Net FrameWork 4.6.1环境下,如何快速使用Spring.Net的IOC功能。话不多说,开撸Demo!

1 准备工作

1.1新建解决方案文件夹,新建BLL、IBLL类库项目:

1.2 在IBLL层中添加测试接口ITest.cs

    public interface ITest
    {
        string GetName();
        int GetAge();
    }

1.3 在BLL层中添加具体的实现类TestBll并继承1.2中接口:

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包:

2.2 在Web.Config文件中配置Spring.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文件,配置如下:

 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等等,希望大家可以支持。

   

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇使用 ASP.NET Core MVC 创建 Web .. 下一篇C#基础复习(4) 之 浅析List、Di..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目