Castle Windsor:从一个程序集中自动注册类型,从而实现另一个程序集的接口
我使用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() .LifeStyle.Singleton
如果在接口上实现基本类型(如IService
,则可以使用以下构造一次注册它们:
AllTypes.FromAssembly(typeof(EmployeeService).Assembly) .BasedOn() .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() );