Spring.Net--控制反转

2020-02-20  本文已影响0人  WxhShine
Spring.jpg

Spring.Net 为建立企业级应用提供了一套轻量级的解决方案。通过Spring.NET,我们可以用统一且透明的方式来配置应用程序。Spring.NET的重点是为中间层提供声明式事务管理,以及一个功能齐全的ASP.NET扩展框架。Spring.NET是非侵入式的,代码对框架本身不会产生任何依赖.

​ Spring.Net 就是抽象工厂模式 , 它使用配置文件的方式,去是实现了控制反转, 控制反转就是通过依赖注入的方式是对象A不需要使用new对象B, 而是通过容器的方式,将对象B注入到对象A的应用.

通过简单的例子来介绍Spring.Net简单的使用:

第一步 : 先新建一个控制台程序;

第二步 : 引入Spring.Net文件,可用在NuGet中搜索,下载.也可以在官网中下载并在项目引用相关.dll文件;

第三步 : 接下来就是创建相关的类文件

using System;

namespace SpringdotNetDemo {
    public class Service1 {
        public string Name { get; set; }
        public Service2 Service { get; set; }
        public void Show() {
            Service.Show();
            Console.WriteLine("Spring.Net:" + Name);
        }
    }
}
using System;

namespace SpringdotNetDemo {
    public class Service2 {
        public void Show() {
            Console.WriteLine("Service2");
        }
    }
}

第四步 : 在App.Config中配置Spring.Net

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <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>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
  </startup>
  <!--Spring.Net 配置-->
  <spring>
    <context>
      <!--容器配置-->
      <resource uri="config://spring/objects"/>
        <!--可以将objects节点的配置保存在xml文件,更改文件更改属性,复制到输出目录:始终复制-->
        <!--<resource uri="file://objects.xml"/>-->
    </context>
    <objects xmlns="http://www.springframework.net">
      <!--这里放容器里面的所有节点-->
      <description>An  example that demonstrates simple IoC features.</description>
      <!--name 必须要唯一的,type=类的全名称,所在的程序集-->
      <object name="Service1" type="SpringdotNetDemo.Serive1, SpringdotNetDemo">
        <!--设置Service1中属性的值-->
        <property name="Name" value="Service1.Name"/>
        <property name="Service" ref="Service2"/>
      </object>
      <object name="Service2" type="SpringdotNetDemo.Serive2, SpringdotNetDemo"></object>
    </objects>
  </spring>

</configuration>

第五步 : 在主函数中应用配置:

using Spring.Context;
using Spring.Context.Support;
using System;

namespace SpringdotNetDemo {
    class Program {
        static void Main(string[] args) {
            //Spring.Net 创建实例的方式转为容器帮我们创建
            //创建spring容器上下文
            IApplicationContext context = ContextRegistry.GetContext();
            //通过容器创建对象
            var ser = context.GetObject("Service1") as Service1;
            ser.Show();
            Console.ReadKey();
        }
    }
}

其运行结果:

Result.jpg

以上就是Spring.Net的简单应用

上一篇下一篇

猜你喜欢

热点阅读