2010-11-01 67 views
10

我使用Castle Windsor作爲我的IoC container。我有一個具有類似於以下結構的應用程序:Castle Windsor:自動註冊從一個組件實現另一個接口的類型

  • MyApp.Services.dll
    • IEmployeeService
    • IContractHoursService
    • ...
  • MyApp.ServicesImpl.dll
    • EmployeeService : MyApp.Services.IEmployeeService
    • ContractHoursService : MyApp.Services.IContractHoursService
    • ...

我使用XML configuration的那一刻,我每次添加一個新的IService /服務對,我有一個新的組件添加到XML配置文件。我想切換到fluent registration API,但還沒有制定出正好正確的配方做我想要的。

任何人都可以幫忙嗎?生活方式將全部爲singleton

非常感謝提前。

回答

12

隨着AllTypes,你可以很容易地做到這一點:

http://stw.castleproject.org/(S(nppam045y0sdncmbazr1ob55))/Windsor.Registering-components-by-conventions.ashx

註冊組件一個接一個可以很重複的工作。同時記住註冊每個你添加的新類型可能會很快導致沮喪。幸運的是,你不必這樣做,至少總是這樣。通過使用AllTypes入口類,您可以根據您指定的某些指定特徵執行類型的組註冊。

我覺得您的註冊看起來像:

AllTypes.FromAssembly(typeof(EmployeeService).Assembly) 
    .BasedOn<IEmployeeService>() 
    .LifeStyle.Singleton 

如果您實現一個基本類型,像IService你的接口,你可以一次按下面的步驟他們都登記:

AllTypes.FromAssembly(typeof(EmployeeService).Assembly) 
    .BasedOn<IService>() 
    .WithService.FromInterface() 
    .LifeStyle.Singleton 

欲瞭解更多示例,請參閱文章。這對可能性有很好的描述。

+0

這並不做100%我需要什麼,雖然。第一個程序集中有不同的服務接口,並且我有一個具體實例的一對一映射。我必須一遍又一遍地編寫上面的代碼,就像我現在爲xml配置一樣。 – 2010-11-01 15:44:51

+0

是否有一個用於'IEmployeeService'的基礎接口?這就是我所做的。您可以告訴Windsor查找該接口,將其下面的所有內容(特別是'IEmployeeService')註冊到該程序集的實現中。用一個例子擴大答案。 – 2010-11-01 15:46:51

+0

你的意思是說有一個簡單的'IService'沒有成員作爲標記接口?這可以工作,我只是希望我能避免它。 :) – 2010-11-01 15:49:35

3

我把Pieter's answer向前只是一點點(鍵值爲,因爲他建議,AllTypes),並想出了這一點:

// Windsor 2.x 
container.Register(
    AllTypes.FromAssemblyNamed("MyApp.ServicesImpl") 
    .Where(type => type.IsPublic) 
    .WithService.FirstInterface() 
    ); 

此經過的所有公共類的MyApp.ServicesImpl.dll組裝和登記每在容器中使用它實現的第一個接口。因爲我需要服務程序集中的所有類,所以我不需要標記界面。

上述作品適用於舊版本的溫莎。目前Castle Windsor documentation for registering components最新的版本提出以下建議:

// Windsor latest 
container.Register(
    AllTypes.FromAssemblyNamed("MyApp.ServicesImpl") 
    .Where(type => type.IsPublic) // Filtering on public isn't really necessary (see comments) but you could put additional filtering here 
    .WithService.DefaultInterface() 
    ); 
+0

你不需要'Where(type => type .IsPublic)'。無論如何,溫莎只會掃描導出的類型(這意味着公共或嵌套的公共)。 – 2010-11-02 12:01:32

+0

我認爲,但我認爲你需要'Where(something)',因爲'WithService'方法不在'FromAssemblyNamed()'的返回值上。哦,除非我有#intellisensefail ...我會檢查... – 2010-11-02 13:49:15

+0

我剛剛檢查過,它絕對不會爲我編譯。由於我目前使用的是較早版本的溫莎,因此我會假定這是最新版本,並更新上述關於溫莎最新的答案。非常感謝您的意見。 :) – 2010-11-02 13:51:00

相關問題