I made a simple test of the Castle Dynamic Proxy library:
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!");
}
}
Now in my interceptor I want to time the function, but its causing a StackOverflowException because I am calling the target method inside the Intercept method, causing an infinite loop:
public class TestInter开发者_StackOverflow中文版ceptor : 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();
}
}
Is there anyway around this, either by 1) stopping the interceptions process altogether, or 2) removing my interceptor after I have used it for what I need, before getting into an infinite loop?
Are you sure that's what you want to do? I've created a timing interceptor as well to see if a method call (such as a DB query) exceeds a threshold, and if so to log it.
Instead of manually invoking the target, just use invocation.Proceed()
to tell it to go ahead with the intercepted call.
My code looks like this:
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
}
}
精彩评论