简体   繁体   中英

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

"Forwarded type" in Castle Windsor means that one (big) implementation serve to multiple (small) interfaces. My problem is an opposite one: how to handle one (big) interface that I have to maintain by multiple (small) implementations?

I need DI container cooperation because I don't want to resolve all dependencies big interface could have just to proxy calls to smaller implementations.

Ideally, I would say "redirect every IBig.SomeMethod(...) to some matching IOneOfSmallOnes.SomeMethod(...) without instantiating any full IBig implementation - just the IOneOfSmallOnes one". Is there a way I can do that without digging too deep into the Castle Windsor code?

I could see implementing this via interceptors , using one interceptor for each of the small interfaces. Using this method, a proxy object is created for IBig and all the method calls are passed to the first interceptor. This interceptor then decides if it wants to handle the method call or just pass it down to the next interceptor in the chain.

One of these interceptors would look like this:

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();
    }
}

And your registration would be simple:

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

Note there's no implementation for IBig (the interceptors provide all of it), and you can register the interceptors with Windsor in the same way you do for any other types (in case you need to supply dependencies).

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM