Search code examples
c#castle-windsorioc-containerinterceptorcastle-dynamicproxy

Castle Windsor intercept method call from within the class


We have components registrations in Castle Windsor container like so

void RegisterComponent<TInterface, TImplementation>() {
    var component = Component.For<TInterface>().ImplementedBy<TImplementation>();
    component.Interceptors<SomeInterceptor>();
    container.Register(component);
}

However we got to the problem that when we do a method call from within the class it does not get intercepted. For example we have component like

ServiceA : IService {

    public void MethodA1() {
        // do some stuff
    }

    public void MethodA2() {
        MethodA1();
    }

}

And if we call MethodA2 or MethodA1 methods from some other class it is intercepted, but MethodA1 apparently not intercepted when called from MethodA2 since the call is from within the class.

We have found similar case with the solution Castle Dynamic Proxy not intercepting method calls when invoked from within the class However the solution features component and proxy creation using new operator which is not suitable in our case since we are using container. Can we use this solution with component registration like above? Or are there other approaches to solve the problem?


Solution

  • For interception to work on MethodA1 when invoked from MethodA2 you need to be using inheritance based interception (it's because you are using this reference to make the invocation).

    To make inheritance based interception possible first you need to make MethodA1 and MethodA2 virtual.

    Then you can make container registration like this:

    container.Register(Component.For<ServiceA>().Interceptors<SomeInterceptor>());
    container.Register(Component.For<IService>().UsingFactoryMethod(c => c.Resolve<ServiceA>()));
    

    First register your service as itself applying interceptors (this will add inheritance based interception over the service). Then you can register the interface which will use service registered earlier.