一个例子最能解释它:为什么DynamicProxy的拦截器不会为每个虚拟方法调用调用?
public interface IA {
void foo();
void bar();
}
public class A : IA {
public virtual void foo(){
Console.Write("foo");
bar(); //call virtual method
}
public virtual void bar(){
Console.Write("bar");
}
}
public class Interceptor : IInterceptor {
public void Intercept(IInvocation invocation)
{
Console.WriteLine("Intercepted: " + invocation.Method.Name);
invocation.Proceed();
}
}
Main(){
IA a = new A();
//proxy-ing an interface, given an implementation
IA proxy = new Castle.DynamicProxy.ProxyGenerator()
.CreateInterfaceProxyWithTarget(a, new Interceptor());
proxy.foo();
}
我本来期望输出:
Intercepted foo
foo
Intercepted bar
bar
相反,我得到:
Intercepted foo
foo
bar
为什么?
动态代理如何工作? 我期待生成的代理从代理类继承,但是,它似乎使用组合将代理接口中的每个方法委托给实际实现。
我试着城堡DynamicProxy,并与旧的动态代理实现,从Cramon
是的,这或多或少是正确的。 – 2010-01-28 10:58:57
哇,你是Castle DynamicProxy宇宙中的摇滚明星:) 感谢您编写教程! (或者我应该说,*教程;) – 2010-01-28 15:14:05