Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Intercept and cancel method execution

Is there a way to intercept a method execution and cancel it? I've only found a way to do it throwing an exception from the Invoke method using Microsoft.Practices.Unity and ICallHandler, but on the Invoke method implementation, I can only return getNext()(input, getNext);.

Bassically this is the code:

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);
    }
}
like image 869
Chuck Norris Avatar asked Dec 26 '22 17:12

Chuck Norris


2 Answers

I would also recommend to look at AOP approach. For example PostSharp. They have a lot of aspects for different use cases. Details here: http://www.sharpcrafters.com You can take a look for MethodInterceptionAspect

like image 23
Mykola Kushnir Avatar answered Dec 29 '22 11:12

Mykola Kushnir


It depends on what you mean by cancelling. The client code has invoked the method and it expects a result or an exception.

What you can do is avoid calling the original method in your handler, effectively stopping the pipeline, but you need to do something to complete the method call.

To bypass the rest of the pipeline, which includes the original method, you need to create a new method return with the CreateMethodReturn method in the IMethodInvocation interface for a successful return or with the CreateExceptionMethodReturn method for throwing an exception. See http://msdn.microsoft.com/en-us/library/ee650526(v=pandp.20) for details.

For example instead of doing

return getNext()(input, getNext);

you could do

return input.CreateMethodReturn(null, input.Arguments)

to return null.

For a general purpose handler, you'd need to analyze the intercepted method signature to figure out what needs to be returned.

like image 63
fsimonazzi Avatar answered Dec 29 '22 09:12

fsimonazzi