在温莎城堡注册多个组件和多个服务

本文关键字:组件 服务 注册 城堡 | 更新日期: 2023-09-27 17:59:53

我在两个分离的程序集中有一些服务和它们的接口,一个用于接口,另一个用于实现。

我正试着用温莎城堡注册他们。它可以完美地使用这样的东西:

 container.Register(Component
.For(IService1)
.ImplementedBy(Service1)
.LifeStyle.Transient());
 container.Register(Component
.For(IService2)
.ImplementedBy(Service2)
.LifeStyle.Transient());

这里的问题是…是否可以同时注册所有组件?无需逐一注册。我已经看到可以将多个接口注册到一个简单的组件,或者为一个接口注册多个实现,但我还没有看到是否可以将一个程序集的多个接口与另一个程序集中的多个实现注册。

我不知道这是否有任何相关性,但所有接口都有相同的基础(本例中为IService)。

非常感谢。

在温莎城堡注册多个组件和多个服务

您想要的是通过约定注册组件。基本上,您所做的是声明Castle应该考虑哪些实现,以及它应该将这些实现与哪些服务相关联。

container.Register(
    // we want all concrete classes in this assembly
    Classes.FromThisAssembly()
    // but we filter them to keep only the ones in a specific namespace
    .InSameNamespaceAs<RootComponent>()
    // we register thoses classes to interfaces that match the classes names
    .WithService.DefaultInterfaces()
    // setting the lifestyles for all components in this batch
    .LifestyleTransient()
);

基于约定的注册还有许多其他选择,最好的方法是长时间查看链接页面。