【问题标题】:Using Castle Dynamic Proxy - Possible to control and/or remove interceptors使用 Castle Dynamic Proxy - 可以控制和/或删除拦截器
【发布时间】:2011-09-30 16:27:16
【问题描述】:

我对 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 方法中调用目标方法,导致无限循环:

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) 在我将拦截器用于我需要的用途之后,然后在进入无限循环之前移除它?

【问题讨论】:

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


    【解决方案1】:

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

    不用手动调用目标,只需使用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
                }
            }
    

    【讨论】:

    • 谢谢,如果我理解正确的话——invocation.Proceed() 总是会调用被拦截的原始方法,对吧?
    • 是的,就是这张票!拦截器可以非常方便。我有几个我们在公司使用的,但我最喜欢的两个记录方法的持续时间,一个记录方法的持续时间,如果它超过阈值(例如,我们想知道我们的任何数据库调用是否超过 2000 毫秒),一种对调试很有用的方法,它记录所有输入参数并将值从作为 xml 拦截的方法返回到日志,如果日志级别 == 调试
    猜你喜欢
    • 1970-01-01
    • 2011-10-03
    • 2018-01-30
    • 2012-06-01
    • 1970-01-01
    • 2011-10-01
    • 2014-08-22
    • 2018-02-05
    • 1970-01-01
    相关资源
    最近更新 更多