2010-09-22 160 views
1

在DLL內部,我們定義了從接口繼承的兩個類(「Class1」和「Class2」)(「IInterface」 )和一個基類(「BaseClass」)。Castle Fluent註冊:無法覆蓋「AllTypes」註冊爲「Component」的類型

我們使用Castle Windsor的Fluent註冊API(http://using.castleproject.org/display/IoC/Fluent+Registration+API)來自動註冊從「BaseClass」(DLL內部)繼承的所有類到它們各自的接口。

對於特定的個性化,我們使用了(自今日起)一個「castle.xml」文件,它覆蓋了接口和具體類之間的關聯(通過「組件」標籤)。我們在WindsorContainer的構造函數中加載該xml文件。

的代碼是這樣的:

 //container's initialization: 
     var resource = new FileResource("Castle.xml"); 
     var interpreter = new XmlInterpreter(resource); 
     var container = new WindsorContainer(interpreter); 
     container.AddFacility<TypedFactoryFacility>(); 

     //... 

     //automatic type registration: 
     container.Register(
      AllTypes 
       .FromAssemblyContaining<BaseClass>() 
       .BasedOn<BaseClass>() 
       .WithService.Select(
        (t1, t2) => t1.GetInterfaces() 
            .Except(new[] {typeof (IDisposable)}) 
            .Union(new[] {t1})) 
       .Configure(a => a.Named(a.ServiceType.Name) 
            .LifeStyle.Transient) 
       .AllowMultipleMatches() 
      ); 

默認情況下,如果我們問城堡爲IInterface對象,我們得到「1類」;要獲得「Class2」,我們必須在「Castle.xml」文件中指定它。

今天,我試圖擺脫castle.xml的,指定的流暢配置裏面的「組件」指令(前「AllTypes」指令):

 container.Register(
      Component 
       .For<IInterface>() 
       .ImplementedBy<Class2>() 
       .LifeStyle.Transient); 

...但我們仍然得到一個Class1對象,就好像「AllTypes」流利指令覆蓋了「Component」一樣(這很奇怪,因爲xml文件中的「component」指令起作用)。

我在做什麼錯?

編輯:我是訪問由鍵值名組件「.Named()」解決了這個問題(感謝克日什托夫):

 container.Register(
      Component 
       .For<IInterface>() 
       .ImplementedBy<Class2>() 
       .Named(typeof(IInterface).Name) 
       .LifeStyle.Transient); 
+2

你使用的是什麼版本?你確定所有組件在你註冊時都被註冊了嗎?你是按類型而不是按名稱解析組件的? – 2010-09-22 13:33:29

+0

@Krzysztof:我正在使用Castle.Microkernel的2.1.0.0版本。事實上,我們使用「return _container.Resolve (key,dictionary)」... ... – Notoriousxl 2010-09-22 13:59:06

+0

@Krzysztof:命名()工作非常好,謝謝!現在我可以殺死所有這些魔術字符串...... :) – Notoriousxl 2010-09-22 15:59:48

回答

1

只是,這樣的問題不會出現無人接聽,該答案在上面的評論中。