Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
488 views
in Technique[技术] by (71.8m points)

c# - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...