在类的内部温莎城堡拦截方法调用 [英] 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();
}
}
如果我们称之为 MethodA2
或 MethodA1
从中截取一些其他类的方法,但 MethodA1
显然不是截获 MethodA2
调用时,因为呼叫从类中。
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?
推荐答案
有关拦截在 MethodA1 $工作C $ C>从
MethodA2
您需要使用基于继承拦截(那是因为你正在使用这个
参考使调用)。
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).
为了使基于继承拦截可能首先你需要做 MethodA1
和 MethodA2
虚拟
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.
这篇关于在类的内部温莎城堡拦截方法调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!