如何将实现泛型接口的接口注册到具有泛型的类

本文关键字:泛型 注册 接口 实现 泛型接口 | 更新日期: 2023-09-27 18:07:00

给出下面的代码,我如何在Castle Windsor(最新版本)中设置注册以使ISomeService解析为SomeDecorator<SomeRequest,> ?

public interface IService<in TRequest, out TResponse>
{
    TResponse Get(TRequest request);
}
public class SomeRequest
{
    public int SomeId { get; set; }
    public int SomeOtherId { get; set; }
}
public class SomeResponse
{
    public int SomeId { get; set; }
    public string SomeName { get; set; }
    public IEnumerable<string> SomeList { get; set; }
}
public interface ISomeService : IService<SomeRequest, SomeResponse> { }
public class SomeService : ISomeService
{
    public SomeResponse Get(SomeRequest request)
    {
        return new SomeResponse { SomeId = request.SomeId, SomeName = "The Name", SomeList = new List<string>() };
    }
}
public class SomeDecorator<TRequest, TResponse> : IService<TRequest, TResponse>
{
    private readonly IService<TRequest, TResponse> _service;
    public SomeDecorator(IService<TRequest, TResponse> service)
    {
        _service = service;
    }
    public TResponse Get(TRequest request)
    {
        //Do something before
        var response = _service.Get(request);
        //Do something after
        return response;
    }
}

通过下面的注册,ISomeService解析为someeservice,而不是SomeDecorator& lt;SomeRequest, SomeResponse>

public void Install(IWindsorContainer container, IConfigurationStore store)
{
    container.Register(Component
        .For(IService<SomeRequest,SomeResponse>)
        .ImplementedBy(ISomeService));
    container.Register(Component
        .For(ISomeService)
        .ImplementedBy(SomeService));
    container.Register(Component
        .For(IService<,>)
        .ImplementedBy(SomeDecorator<,>)
        .IsDefault());
}

当我尝试注册ISomeService由SomeDecorator<somerrequest,>,我得到以下错误消息:

无法将类型'SomeDecorator ' 2[SomeRequest, somerresponse]'的对象强制转换为类型'ISomeService'。

如何将实现泛型接口的接口注册到具有泛型的类

有一种方法可以让它工作。这个解决方案的缺点是,你必须针对你想要装饰的每个类注册装饰器。

正如我在上面的评论中所说,你可以通过摆脱ISomeService而使用public class SomeService : IService<SomeRequest, SomeResponse>来简化你的设计。然后,装饰器的注册看起来像这样:

container.Register(
    Component.For<IService<SomeRequest, SomeResponse>>()
        .ImplementedBy<SomeDecorator<SomeRequest, SomeResponse>>(),
    Component.For<IService<SomeRequest, SomeResponse>>()
        .ImplementedBy<SomeService>());

还需要注意的是,你可以用LINQ查询自动注册所有的通用实现。