Dependency Injection using Spring.NET

Dependency Injection using Spring.NET

看了CodeProject上的「Dependency Injection using Spring.NET」,還蠻簡單易懂的,對於要使用Spring.NET的初學者很有幫助哦!

這篇作者以3層式架構來說明如何透過Spring的IApplicationContext來動態建立物件(類似工廠模式),而要建立的物件,則定義在config之中。

image


namespace DAL
{
    public class CustomerDAL : IDAL
    {

        public DataTable GetAll()
        {
            DataTable customerList = new DataTable("customerList");
            customerList.Columns.Add("id", Type.GetType("System.String"));
            customerList.Columns.Add("name", Type.GetType("System.String"));
            customerList.Rows.Add(new string[] {"1", "打死釘" });
            customerList.Rows.Add(new string[] { "2", "郭小玉" });
            customerList.Rows.Add(new string[] { "3", "亂馬客" });
            return customerList;
        }

        public DataTable GetById(string ID)
        {
            throw new NotImplementedException();
        }
    }
}
namespace DAL
{
    public class CustomerDAL2 : IDAL
    {
        public System.Data.DataTable GetAll()
        {
            DataTable customerList = new DataTable("customerList");
            customerList.Columns.Add("id", Type.GetType("System.String"));
            customerList.Columns.Add("name", Type.GetType("System.String"));
            customerList.Rows.Add(new string[] { "1", "打死釘 DAL2" });
            customerList.Rows.Add(new string[] { "2", "郭小玉 DAL2" });
            customerList.Rows.Add(new string[] { "3", "亂馬客 DAL2" });
            return customerList;
        }

        public System.Data.DataTable GetById(string ID)
        {
            throw new NotImplementedException();
        }
    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using Spring.Context;
using Spring.Context.Support;
using DAL;

namespace BLL
{
    public class CustomerBLL :IBLL
    {
        public DataTable GetAll()
        {
            IApplicationContext appContext = ContextRegistry.GetContext();
            IDAL customerDAL = appContext["CustomerDAL"] as IDAL;
            return customerDAL.GetAll();
        }

        public DataTable GetById(string ID)
        {
            throw new NotImplementedException();
        }
    }
}

所以當我要換任何物件,只要Interface沒有變,都可以透過config的設定來改變(如將DAL.CustomerDAL換成DAL.CustomerDAL2)。

image

範例程式:

Hi, 

亂馬客Blog已移到了 「亂馬客​ : Re:從零開始的軟體開發生活

請大家繼續支持 ^_^