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);
}
}
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With