10

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

提前谢谢了。

4

2 回答 2

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

有关更多示例,请参阅文章。这很好地描述了可能性。

于 2010-11-01T15:39:19.403 回答
5

我将Pieter 的答案向前一点点(关键是,正如他所建议的那样AllTypes)并提出了这个:

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

这会遍历程序集中的所有公共类,MyApp.ServicesImpl.dll并使用它实现的第一个接口在容器中注册每个类。因为我想要服务程序集中的所有类,所以我不需要标记接口。

以上适用于旧版本的温莎。当前用于为最新版本注册组件的 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()
    );
于 2010-11-02T09:09:37.930 回答