【发布时间】:2011-10-01 19:29:29
【问题描述】:
在使用 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 中调用。
我可以理解,当从代理类中进行调用时,它将不再通过代理,但只是想检查这是否是预期的,如果是,那么看看是否有任何方法可以获取所有调用无论从哪里调用都被拦截?
谢谢
【问题讨论】:
标签: c# castle-dynamicproxy dynamic-proxy