对于特定的控制器,Windsor实例化不同的类

que*_*en3 3 asp.net-mvc castle-windsor ioc-container sharp-architecture

我使用S#arp架构,它使用Windsor Castle作为IoC.我现在有一个新的控制器,与项目中的所有其他控制器不同,需要不同的相同接口实现.即所有控制器都使用ProductsRepository:IProductsRepository作为实现,但新的控制器必须使用SpecificProductsRepository.

如何将其配置为自动识别和管理?无论是纯粹的Windsor方式,还是ASP.NET MVC帮助(例如在我的自定义控制器工厂中).

好像我需要子容器.仍在搜索中.

moo*_*000 6

一种更简单,更简单的方法是使用Windsor的服务覆盖.

例如,如下注册你的回购:

container.Register(Component.For<IProductsRepository>
                     .ImplementedBy<ProductsRepository>()
                     .Named("defaultProductsRepository"),
                   Component.For<IProductsRepository>
                     .ImplementedBy<SpecificProductsRepository>()
                     .Named("specificProductsRepository"));
Run Code Online (Sandbox Code Playgroud)

这将确保默认实现ProductsRepository.现在,对于您的特定控制器,添加如下所示的服务覆盖:

container.Register(Component.For<NewController>()
     .ServiceOverrides(ServiceOverride
          .ForKey("productsRepository")
          .Eq("specificProductsRepository"));
Run Code Online (Sandbox Code Playgroud)

你可以在这里阅读文档.

编辑:如果您想注册您的存储库AllTypes,您可以调整注册密钥,例如:

container.Register(AllTypes.[how you used to].Configure(c => c.Named(GetKey(c)));
Run Code Online (Sandbox Code Playgroud)

其中,GetKey例如,可能是这样的:

public string GetKey(ComponentRegistration registration)
{
    return registration.Implementation.Name;
}
Run Code Online (Sandbox Code Playgroud)