Click or drag to resize

IMethodInterceptor Interface

Represents a method interceptor. This interceptor can also be applied to abstract methods and all overriding methods will implement this interceptor.

Namespace:  Cauldron.Interception
Assembly:  Cauldron.Interception (in Cauldron.Interception.dll) Version: 1.0.0
Syntax
public interface IMethodInterceptor

The IMethodInterceptor type exposes the following members.

Methods
  NameDescription
Public methodOnEnter
Invoked if an intercepted method has been called
Public methodOnException
Invoked if an intercepted method has raised an exception.
Public methodOnExit
Invoked if the intercepted method has finished executing.
Top
Examples
Sample implementation:
[InterceptorOptions(AlwaysCreateNewInstance = true)]
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
public class MyInterceptorAttribute : Attribute, IMethodInterceptor
{
    public void OnEnter(Type declaringType, object instance, MethodBase methodbase, object[] values)
    {
    }

    public bool OnException(Exception e)
    {
        // Returning false will swallow the exception
        return true;
    }

    public void OnExit()
    {
    }
}
The interceptor is also capable of handling attributes with parameters.

Your code:

public class SampleClass
{
    [MyInterceptor]
    public void SampleMethod()
    {
        Debug.WriteLine("Blablablablablabla");
    }
}
What gets compiled:
public class SampleClass
{
    public void SampleMethod()
    {
        var interceptorAttribute = new MyInterceptorAttribute();

        try
        {
            interceptorAttribute.OnEnter(typeof(SampleClass), this, MethodBase.GetMethodFromHandle(methodof(SampleClass.SampleMethod()).MethodHandle, typeof(SampleClass).TypeHandle), new object[0]);
            Debug.WriteLine("Blablablablablabla");
        }
        catch (Exception e)
        {
            if(interceptorAttribute.OnException(e))
            {
                throw;
            }
        }
        finally
        {
            interceptorAttribute.OnExit();
        }
    }
}
See Also