Spring.NET依赖注入(二) - 对象的注入

1. 抽象注入接口

public interface IDeviceWriter
    {
        void saveToDevice();
    }

 

2. 接口的具体实现

  实现1

public class FloppyWriter : IDeviceWriter
    {
        public void saveToDevice() 
        {
            Console.WriteLine("储存至软盘…");
        }
    }

 

  实现2

public class UsbDiskWriter : IDeviceWriter
    {
        public void saveToDevice() 
        {
            Console.WriteLine("储存至移动硬盘…");
        }
    }

 

3. 需要注入的业务对象

public class MemoryDevice
    {
        public IDeviceWriter DeviceWriter { getset; }

        public void Save()
        {
            if (DeviceWriter == null)
            {
                throw new Exception("需要设备...");
            }

            DeviceWriter.saveToDevice();
        }
    }

 

4. 业务调用组件

public class DeviceComponent
    {
        public static void SaveDevice()
        {
            try
            {
                //从config文件中取得程序集信息
                IApplicationContext context = ConfigurationManager.GetSection("spring/context"as IApplicationContext;

                //调用方法
                MemoryDevice device = context.GetObject("algDevice"as MemoryDevice;
                device.Save();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }

 

5. 客户端调用

class SpringDeviceTest : ITestCase
    {
        public void Run()
        {
            DeviceComponent.SaveDevice();

            Console.Read();
        }
    }

 

6. 配置文件

<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>
    <context>
      <resource uri="config://spring/objects"/>
    </context>
    
    <objects>
     ...
     <object id="algFloppy" type="CsharpTrainer.Strategy.Device.FloppyWriter, CsharpTrainer.Strategy" />
      <object id="algUsb" type="CsharpTrainer.Strategy.Device.UsbDiskWriter, CsharpTrainer.Strategy" />
      <object id="algDevice" type="CsharpTrainer.Strategy.Device.MemoryDevice, CsharpTrainer.Strategy">
        <property name="DeviceWriter" ref="algFloppy" />
        <!--<property name="DeviceWriter" ref="algUsb" />-->
      </object>
    </objects>
  </spring>
  ...
</configuration>

 

7. 运行结果

  储存至软盘…

 

上一篇:手写类似dubbo的rpc框架第三章《rpc框架》


下一篇:netty案例,netty4.1中级拓展篇二《Netty使用Protobuf传输数据》