一个例子能最好地解释它:
相反,我得到:
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
为什么?
动态代理是如何工作的? 我原以为生成的代理会从被代理的类中继承,但似乎它使用组合将被代理接口中的每个方法委托给实际实现。
我已经尝试过Castle DynamicProxy和一个较旧的动态代理实现,来自Cramon。