簡體   English   中英

Castle Windsor:從一個程序集中自動注冊類型,從而實現另一個程序集的接口

[英]Castle Windsor: Auto-register types from one assembly that implement interfaces from another

我使用Castle Windsor作為我的IoC容器 我有一個具有類似於以下結構的應用程序:

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

我目前使用XML配置 ,每次添加新的IService / Service對時,我都需要在XML配置文件中添加一個新組件。 我想將所有這些切換到流暢的注冊API,但還沒有找到完全正確的配方來做我想要的。

有人可以幫忙嗎? 生活方式都是singleton

提前謝謝了。

使用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

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

我把Pieter的答案向前推了一點(正如他所建議的那樣,關鍵是AllTypes ),並提出了這個問題:

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

這將遍歷MyApp.ServicesImpl.dll程序MyApp.ServicesImpl.dll所有公共類,並使用它實現的第一個接口在容器中注冊每個類。 因為我想要服務程序集中的所有類,所以我不需要標記接口。

以上適用於舊版Windsor。 用於注冊最新版本組件的當前Castle Windsor文檔建議如下:

// 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()
    );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM