使用Castle动态代理 - 可以控制和/或删除拦截器

时间:2011-07-07 17:43:16

标签: c# reflection castle-windsor interceptor castle-dynamicproxy

我对Castle Dynamic Proxy库进行了简单的测试:

public class Printer
{
    public virtual void Write(string msg)
    {
        Console.Write(msg); 
    }
}

public class CastleDynamicProxy
{
    public static void Test()
    {
        ProxyGenerator generator = new ProxyGenerator();

        Printer logger = generator.CreateClassProxy<Printer>(new TestInterceptor());

        logger.Write("Hello, World!"); 
    }
}

现在在我的拦截器中我想对函数计时,但是它导致了StackOverflowException,因为我在Intercept方法中调用了target方法,导致无限循环:

public class TestInterceptor : IInterceptor
{
    public void Intercept(IInvocation invocation)
    {
       var accessor = invocation.Proxy as IProxyTargetAccessor;

       MethodInfo target = accessor.DynProxyGetTarget().GetType().GetMethod("Write"); 

       var s = Stopwatch.StartNew(); 

       target.Invoke(invocation.InvocationTarget, invocation.Arguments);

       s.Stop(); 
    }
}

无论如何都要围绕这个,或者1)完全停止拦截过程,或者2)在我进入无限循环之前将其用于我所需要的之后移除我的拦截器?

1 个答案:

答案 0 :(得分:3)

你确定这是你想做的吗?我也创建了一个计时拦截器,以查看方法调用(例如数据库查询)是否超过阈值,如果是,则记录它。

不要手动调用目标,只需使用invocation.Proceed()告诉它继续拦截调用。

我的代码如下所示:

        public void Intercept(IInvocation invocation)
        {
            var timer = Stopwatch.StartNew();

            // i think you want this to proceed with the invocation...
            invocation.Proceed();

            timer.Stop();

            // check if threshold is exceeded
            if (timer.Elapsed > _threshold)
            {
                // log it to logger of choice
            }
        }
相关问题