Spring.Net学习笔记(2)-依赖注入 一、开发环境 二、涉及程序集 三、项目结构 四、开发过程 五、程序说明 六、参考文章

操作系统:Win10

编译器:VS2013

framework版本:.net 4.5

Spring版本:1.3.1

二、涉及程序集

Spring.Core.dll

Common.Loggin.dll

三、项目结构

Spring.Net学习笔记(2)-依赖注入
一、开发环境
二、涉及程序集
三、项目结构
四、开发过程
五、程序说明
六、参考文章

四、开发过程

1.新建一个接口文件

namespace SpringNetIoc.IScene
{
    public interface IBall
    {
        void DoSport();
    }
}

2.新建两个实现接口IBall的具体类

namespace SpringNetIoc.Scene
{
  public  class Basketball:IBall
    {
        public void DoSport()
        {
            Console.WriteLine("打篮球");
        }
    }
}
namespace SpringNetIoc.Scene
{
    public class Tennis : IBall
    {
        public void DoSport()
        {
            Console.WriteLine("打网球");
        }
    }
}

3.新建一个Person类

namespace SpringNetIoc.Role
{
    public class Person
    {
        public IBall Ball { get; set; }

        public void Hobby()
        {
            Ball.DoSport();
        }
    }
}

4.配置Spring.net

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <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 xmlns="http://www.springframework.net">
    <context>
      <resource uri="config://spring/objects"></resource>
    </context>
    <objects xmlns="http://www.springframework.net">
      <object name="basketball" type="SpringNetIoc.Scene.Basketball,SpringNetIoc"></object>
      <object name="tennis" type="SpringNetIoc.Scene.Tennis,SpringNetIoc"></object>
      <object name="person" type="SpringNetIoc.Role.Person,SpringNetIoc">
        <!--<property name="Ball" ref="basketball"></property>-->
        <property name="Ball" ref="tennis"></property>
      </object>
    </objects>
  </spring>
  
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
  </startup>
</configuration>

5.在控制台中,输出结果

namespace SpringNetIoc
{
    class Program
    {
        static void Main(string[] args)
        {
            IApplicationContext context = ContextRegistry.GetContext();
            Person person = context.GetObject("person") as Person;
            person.Hobby();
            Console.Read();
        }
    }
}

五、程序说明

在一定程度上解决了Person与IBall耦合的问题,但是实际上并没有完全解决耦合,只是把耦合放到了xml文件中。通过一个容器在需要的时候把这个依赖关系形成,即把需要的接口实现注入到需要它的类中。IoC模式可以看做是:容器+工厂。只不过这个大工厂里要生成的对象都是在xml文件中给出定义的。

六、参考文章

http://www.cnblogs.com/GoodHelper/archive/2009/10/26/SpringNET_DI.html