天天看點

Spring.NET依賴注入(二) - 對象的注入

1. 抽象注入接口

public interface IDeviceWriter

    {

        void saveToDevice();

    }

2. 接口的具體實作

  實作1

public class FloppyWriter : IDeviceWriter

        public void saveToDevice() 

        {

            Console.WriteLine("儲存至軟碟…");

        }

  實作2

public class UsbDiskWriter : IDeviceWriter

            Console.WriteLine("儲存至移動硬碟…");

3. 需要注入的業務對象

public class MemoryDevice

        public IDeviceWriter DeviceWriter { get; set; }

        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. 運作結果

  儲存至軟碟…