码迷,mamicode.com
首页 > 编程语言 > 详细

Spring.Net学习笔记(2)-依赖注入

时间:2016-03-13 22:26:47      阅读:295      评论:0      收藏:0      [点我收藏+]

标签:

一、开发环境

操作系统:Win10

编译器:VS2013

framework版本:.net 4.5

Spring版本:1.3.1

二、涉及程序集

Spring.Core.dll

Common.Loggin.dll

三、项目结构

技术分享

四、开发过程

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

Spring.Net学习笔记(2)-依赖注入

标签:

原文地址:http://www.cnblogs.com/2star/p/5273261.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!