How to intercept and cancel method execution

Is there a way to intercept method execution and cancel ? I found a way to do this by excluding Invoke using Microsoft.Practices.Unity and ICallHandler , but in the implementation of the Invoke method I can only return getNext()(input, getNext); .

Basically this is the code:

 public class TestHandler : ICallHandler { public int Order { get; set; } public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { Console.WriteLine("It been intercepted."); // Here... please Lord, tell me I can cancel it, I'm a good person. return getNext()(input, getNext); } } 
+4
source share
2 answers

It depends on what you mean by cancellation. Client code has called a method and expects a result or exception.

What you can do is to 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 that includes the original method, you need to create a new return method using the CreateMethodReturn method in the IMethodInvocation interface to return successfully or using the CreateExceptionMethodReturn method to throw an exception. See http://msdn.microsoft.com/en-us/library/ee650526(v=pandp.20) for more details.

For example, instead of executing

 return getNext()(input, getNext); 

you could do

 return input.CreateMethodReturn(null, input.Arguments) 

to return null.

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

+6
source

I would also recommend looking at the AOP approach. For example, PostSharp. They have many aspects for different use cases. Details here: http://www.sharpcrafters.com You can look at MethodInterceptionAspect

+3
source

Source: https://habr.com/ru/post/1434299/


All Articles