如何拦截和取消方法执行

Chu*_*ris 4 c# aop unity-container interceptor

有没有办法拦截方法执行并取消它?我只是找到了一种Invoke方法来使用Microsoft.Practices.Unity和从方法中抛出异常ICallHandler,但是在Invoke方法实现上,我只能返回getNext()(input, getNext);.

这是代码:

public class TestHandler : ICallHandler
{
    public int Order { get; set; }

    public IMethodReturn Invoke(IMethodInvocation input, 
                                GetNextHandlerDelegate getNext)
    {
        Console.WriteLine("It's been intercepted.");

        // Here... please Lord, tell me I can cancel it, I'm a good person.
        return getNext()(input, getNext);
    }
}
Run Code Online (Sandbox Code Playgroud)

fsi*_*zzi 6

这取决于取消你的意思.客户端代码已调用该方法,并且它期望结果或异常.

你可以做的是避免在你的处理程序中调用原始方法,有效地停止管道,但你需要做一些事情来完成方法调用.

要绕过包含原始方法的其余管道,您需要使用IMethodInvocation接口中的CreateMethodReturn方法创建一个新方法返回,以便成功返回,或者使用CreateExceptionMethodReturn方法抛出异常.有关详细信息,请参阅http://msdn.microsoft.com/en-us/library/ee650526(v=pandp.20).

例如,而不是做

return getNext()(input, getNext);
Run Code Online (Sandbox Code Playgroud)

你能做到的

return input.CreateMethodReturn(null, input.Arguments)
Run Code Online (Sandbox Code Playgroud)

返回null.

对于通用处理程序,您需要分析截获的方法签名以确定需要返回的内容.