Reference
You can develop an OnMethodInvocation aspect by
deriving the custom attribute OnMethodInvocationAspect
or by implementing the interface IOnMethodInvocationAspect.
Overview
Like the OnMethodBoundary aspect, the
OnMethodInvocation aspect allows you to add behaviors
to method. The difference is that OnMethodInvocation
does not modify the original method, but intercepts method
invocations and invokes your handler (OnInvocation)
instead of the original method.
The OnInvocation handler receives an MethodInvocationEventArgs
object. The method Proceed
invokes the original method. Note that the default implementation
of the OnInvocation handler is to call
Proceed, so you should not call Proceed
if you already call base.OnInvocation, and
conversely.
Getting arguments and invoking the intercepted method
A delegate to the original method is exposed on the property
Delegate.
You can get a array of parameters by calling the GetArgumentArray
method of the MethodInvocationEventArgs
object. This array is writable, so you can change the value of
arguments passed by reference (ref or out
keywords in C#). The return value should be written in the ReturnValue
property.
Therefore, the following code is equivalent to calling the
Proceed method:
eventArgs.ReturnValue = eventArgs.Delegate.DynamicInvoke( eventArgs.GetArgumentArray() );
Call-site weaving and target-site weaving
There are two ways to catch a method interception:
Call-site weaving
We can modify each call instruction. This is called
call-site weaving.
The advantage of call-site weaving is
that we can apply behaviors to methods that are not defined in the
current assembly. We can for instance monitor all calls to methods
of the System.Threading namespace.
The disadvantage is that aspects are not applied when the method is called from another assembly than the current one, or when the method is invoked through a delegate.
Target-site weaving
Alternatively, we can rename the original method and create a new method, with identical name signature, that contains the interception logic.
The advantages and disadvantages of target-site weaving are exactly the opposite of call-site weaving. Aspects will be applied when the method will be invoked from outside the assembly or from a delegate. However, we can intercept only calls done from the current assembly.
Overriding the default behavior
The default behavior of the OnMethodInvocation
aspect is to use target-site weaving when the method is defined in
the current assembly, and call-site weaving when the method is
defined in a different assembly.
You can override this behavior by implementing the GetOptions
method of the MethodInvocationEventArgs
object.
Applying multiple OnMethodInvocation aspects to the same method
This is unfortunately not possible with the current version.