Castle Windsor 可以帮我拆分一个大接口的实现吗?

Can Castle Windsor help me to split implementation of a big interface?

"Forwarded type" 在 Castle Windsor 中意味着一个(大)实现服务于多个(小)接口。我的问题是相反的:如何处理我必须由多个(小)实现维护的一个(大)接口?

我需要 DI 容器协作,因为我不想解决所有依赖关系,大接口可能只需要代理对较小实现的调用。

理想情况下,我会说 "redirect every IBig.SomeMethod(...) to some matching IOneOfSmallOnes.SomeMethod(...) without instantiating any full IBig implementation - just the IOneOfSmallOnes one"。有没有一种方法可以在不深入挖掘温莎城堡代码的情况下做到这一点?

我可以通过 interceptors 实现这一点,为每个小接口使用一个拦截器。使用此方法,为 IBig 创建一个代理对象,并将所有方法调用传递给第一个拦截器。然后这个拦截器决定它是要处理方法调用还是只是将它传递给链中的下一个拦截器。

其中一个拦截器如下所示:

public class FirstSmallInterceptor : Castle.DynamicProxy.IInterceptor
{
    public FirstSmallInterceptor(IFirstSmallOne firstSmallOne) { ... }

    public void Intercept(IInvocation invocation)
    {
        if (invocation.Method.Name == nameof((IFirstSmallOne.FirstSomeMethod))
            invocation.ReturnValue = firstSmallOne.FirstSomeMethod(/* cast invocation.Arguments items */);
        else
            invocation.Proceed();
    }
}

而且您的注册很简单:

container.Register(Component.For<IBig>()
                            .Interceptors(
                                InterceptorReference.ForType<FirstSmallInterceptor>(),
                                InterceptorReference.ForType<SecondSmallInterceptor>(),
                                InterceptorReference.ForType<ThirdSmallInterceptor>()
                             ));

请注意 IBig 没有实现(拦截器提供了所有这些),您可以像注册任何其他类型一样向 Windsor 注册拦截器(以防您需要提供依赖项).

受 Patrick 方法的启发,我实现了 InterfaceSplittingFacility