程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> 關於.NET >> Castle IOC容器與Spring.NET配置之比較

Castle IOC容器與Spring.NET配置之比較

編輯:關於.NET

我本人對於Spring.NET並不了解,本文只是通過一個簡單的例子來比較一下兩者配置之間的區別。在Castle IOC容器中,提出了自動裝配(Auto-Wiring)的概念,即由容器自動管理組件之間的依賴關系,我們無需自己編寫XML配置文件來配置組件之間的依賴關系。在Spring.NET中也是支持自動裝配的,但是並不推薦使用,它貫穿著一種思想就是一切皆為XML配置,這是兩者之間最大的一個區別。

關於自動裝配,來自於Spring.NET的支持者認為讓容器自動管理,會讓我們無法控制組件的依賴關系,如果該為XML配置,可以讓我們知道自己在做什麼,我們指定了哪些依賴關系,方便進行控制和管理;而來自於Castle IOC的支持者認為如果不讓容器自動管理,手工配置會變得非常之復雜,配置文件也會變得非常繁冗,如果系統中的組件非常之多的時候,管理工作會變得很困難。

我們來看一個簡單的例子,有這樣一個組件MyMainComponent,它依賴於MyComponent1、MyComponent2,並且它在構造函數中還需要接收一個整型的參數。

//出處:http://terrylee.cnblogs.com
public class MyMainComponent
{
  MyComponent1 _com1;
  MyComponent2 _com2;
  int _i;
  public MyMainComponent(MyComponent1 com1,MyComponent2 com2,int i)
  {
    this._com1 = com1;
    this._com2 = com2;
    this._i = i;
  }
}
public class MyComponent1
{
  public MyComponent1()
  {
    //
  }
}
public class MyComponent2
{
  public MyComponent2()
  {
    //
  }
}

如果用采用Spring.NET,它采用XML進行組件之間的連接,配置文件如下,需要在配置文件中指定每一個對象及其它們之間的依賴,同時在配置文件中區分是構造函數還是其他方法:

<!--出處:http://terrylee.cnblogs.com-->
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <object id="myManComponent" class="CastleDemo.MyMainComponent, CastleDemo">
    <constructor-arg>
      <ref object="mycomponent1" />
    </constructor-arg>
    <constructor-arg>
      <ref object="mycomponent2" />
    </constructor-arg>
    <constructor-arg>
      <value>1</value>
    </constructor-arg>
  </object>
  <object id="mycomponent1" class="CastleDemo.MyComponent1, CastleDemo" />
  <object id="mycomponent2" class="CastleDemo.MyComponent2, CastleDemo" />
</configuration>

Castle IOC中同樣需要配置文件,但相比之下,就簡單了很多:

<!--出處:http://terrylee.cnblogs.com-->
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <components>
    <component id="myMainComponent">
      <parameters>
        <i>1</i>
      </parameters>
    </component>
  </components>
</configuration>

在Castle IOC中的配置並不需要指定組件之間的關聯,它會自動通過Windsor來處理;我們只是配置了一個參數i,這個i是MyMainComponent中的構造函數中不存在依賴關系的那個參數。

//出處:http://terrylee.cnblogs.com
public class App
{
  public static void Main()
  {
    IWindsorContainer container = new WindsorContainer(new XmlInterpreter("../../BasicUsage.xml") );
    container.AddComponent( "myMainComponent",
      typeof(MyMainComponent));
    container.AddComponent( "myComponent1",
      typeof(MyComponent1));
    container.AddComponent( "myComponent2",
      typeof(MyComponent2));     
  }
}

這樣添加組件後,WindsorContainer會自動調用MicroKernel中的ConstructorDependenciesModelInspector來處理組件的構造函數依賴。

通過上面的這個簡單例子比較可以看出,如果我們想要增加一個組件之間的依賴關系或者增加一個組件使用Castle要比使用Spring.NET容易很多,Spring.NET復雜的配置文件會給我們開發帶來很來不可預料的錯誤;Castle根據對象的依賴關系,采用自動裝配,不需要配置組件的依賴,另外為了符合構造注入和屬性注入,Castle的配置文件並沒有像Spring.Net那樣區分構造函數還是其他的方法,同時直接使用Parameters,而不是使用構造函數參數之類的區分。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved