Nei*_*ell 10 c# castle-windsor fluent-interface ioc-container
我使用Castle Windsor作为我的IoC容器.我有一个具有类似于以下结构的应用程序:
IEmployeeServiceIContractHoursService...EmployeeService : MyApp.Services.IEmployeeServiceContractHoursService : MyApp.Services.IContractHoursService...我目前使用XML配置,每次添加新的IService/Service对时,我都需要在XML配置文件中添加一个新组件.我想将所有这些切换到流畅的注册API,但还没有找到完全正确的配方来做我想要的.
有人可以帮忙吗?生活方式都将是singleton.
提前谢谢了.
Pie*_*kel 12
有了AllTypes你可以很容易地做到这一点:
逐个注册组件可能是非常重复的工作.还记得注册你添加的每个新类型很快就会导致沮丧.幸运的是,至少你总是不必这样做.通过使用AllTypes条目类,您可以根据指定的某些指定特征执行类型的组注册.
我认为你的注册看起来像:
AllTypes.FromAssembly(typeof(EmployeeService).Assembly)
.BasedOn<IEmployeeService>()
.LifeStyle.Singleton
Run Code Online (Sandbox Code Playgroud)
如果IService在接口上实现基类型,则可以使用以下构造一次注册它们:
AllTypes.FromAssembly(typeof(EmployeeService).Assembly)
.BasedOn<IService>()
.WithService.FromInterface()
.LifeStyle.Singleton
Run Code Online (Sandbox Code Playgroud)
有关更多示例,请参阅文章.这对可能性有很好的描述.
我将彼得的答案向前推进了一点(关键是,正如他所建议的那样AllTypes)并提出了这个:
// Windsor 2.x
container.Register(
AllTypes.FromAssemblyNamed("MyApp.ServicesImpl")
.Where(type => type.IsPublic)
.WithService.FirstInterface()
);
Run Code Online (Sandbox Code Playgroud)
这将遍历程序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()
);
Run Code Online (Sandbox Code Playgroud)