c# - CaSTLe Windsor 注册匹配相同服务的组件

标签 c# asp.net-mvc castle-windsor

我的 MVC 应用程序中有以下代码可以正常工作。

container.Register(Component.For<CountryServiceBase>()
    .ImplementedBy<CountryService>()
    .LifestylePerWebRequest());

CaSTLe Windsor 创建一个组件

CountryService / CountryServiceBase

我的 Controller 在这里获取一个实例化对象:

public class MyController : MainController
{
    public CountryServiceBase CountryService {get; set;} // instantiate by Ioc : OK

我的问题是我有很多类(class)要注册。所以我使用 CaSTLe Windsor 做了以下事情:

container.Register(
    Types
    .FromAssemblyNamed("mynamespace")
    .BasedOn(typeof(ServiceBase<>))
    .WithService.Base()
    .LifestylePerWebRequest());

CaSTLe Windsor 创建我的组件

CountryService / ServiceBase<Country>
CountryServiceBase / ServiceBase<Country>

但是我的 MVC 应用程序等待 CountryService/CountryServiceBase,我不知道如何向 CaSTLe Windsor 指定它可以将 CountryServiceBase 匹配回 CountryService,因为这两个类(其中一个是抽象类)继承了 ServiceBase

有可能吗?

注意:我发布了一个类似的问题,但我的调查得出了一个更准确的问题,所以我删除了旧的问题。

最佳答案

通常 services是接口(interface)。这就是为什么 AllInterfaces()为别人工作。

如果您检查 API,您会发现 Select()易于使用的方法。

If none of the above options suits you you can provide your own selection logic as a delegate and pass it to WithService.Select() method.

所以注册码可以是这样的:

    container.Register(Types.FromThisAssembly()
        .BasedOn(typeof(ServiceBase<>))
        .WithService.AllInterfaces()
        .WithService.Select((t, b) => t.BaseType != null
                ? new[] { t.BaseType }
                : new Type[0])
        .LifestylePerWebRequest());

此解决方案非常快捷,但至少可以解决您的问题。

关于c# - CaSTLe Windsor 注册匹配相同服务的组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30806393/

相关文章:

c# - LINQ最适用于哪些场景?

c# - Azure 媒体服务 - 生成新的 AES 加密 token 用于播放

caSTLe-windsor - 根据 CaSTLe Windsor 中的名称约定动态解析

asp.net-mvc-4 - 可以使用 CaSTLe Windsor 在 ASP.NET MVC 4 中实现 IDependencyResolver 吗?

c# - 已处理死信队列中的 MSMQ 无效签名错误

c# - 如何发送带有替代 View 的电子邮件,无论是纯文本还是 HTML 模板。?

c# - 隐式类型转换和多态

asp.net-mvc - ASP.NET MVC 唯一性验证

javascript - Ajax 调用未到达 Controller 方法

c# - 创建递归嵌套实体的类型化工厂设施