在使用 Castle 的动态代理时,我遇到了一些(我认为是)奇怪的行为。
使用以下代码:
class Program
{
static void Main(string[] args)
{
var c = new InterceptedClass();
var i = new Interceptor();
var cp = new ProxyGenerator().CreateClassProxyWithTarget(c, i);
cp.Method1();
cp.Method2();
Console.ReadLine();
}
}
public class Interceptor : IInterceptor
{
public void Intercept(IInvocation invocation)
{
Console.WriteLine(string.Format("Intercepted call to: " + invocation.Method.Name));
invocation.Proceed();
}
}
public class InterceptedClass
{
public virtual void Method1()
{
Console.WriteLine("Called Method 1");
Method2();
}
public virtual void Method2()
{
Console.WriteLine("Called Method 2");
}
}
我期待得到输出:
- 拦截调用:Method1
- 调用方法 1
- 拦截调用:Method2
- 调用方法 2
- 拦截调用:Method2
- 调用方法 2
然而我得到的是:
- 拦截调用:Method1
- 调用方法 1
- 调用方法 2
- 拦截调用:Method2
- 调用方法 2
据我所知,如果调用来自类本身之外,动态代理只能代理方法调用,因为 Method2 在从 Program 调用时被拦截,而不是从 InterceptedClass 中调用。
我可以理解,当从代理类中进行调用时,它将不再通过代理,而只是想检查这是否是预期的,如果是这样,那么看看是否有无论如何都可以拦截所有调用他们是从哪里来的?
谢谢