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. 运行结果

  储存至软盘…

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值