Click or drag to resize

IConstructorInterceptor Interface

Represents a contructor interceptor.

Please note that ISyncRoot is NOT supported by this interceptor.

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

The IConstructorInterceptor type exposes the following members.

Methods
  NameDescription
Public methodOnBeforeInitialization
Invoked before the initialization of the class.

This happens before the base call which means that the instance has not been created yet. Use this with care.

Public methodOnEnter
Invoked if an intercepted contructor has been called.
Public methodOnException
Invoked if an intercepted construtor has raised an exception. The constructor will always rethrow the exception.
Public methodOnExit
Invoked if the intercepted constructor has finished executing.
Top
Examples
Sample implementation:
[AttributeUsage(AttributeTargets.Constructor, AllowMultiple = false, Inherited = false)]
public sealed class TestConstructorInterceptorA : Attribute, IConstructorInterceptor
{
    public void OnBeforeInitialization(Type declaringType, MethodBase methodbase, object[] values)
    {
    }

    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 ConstructorInterceptorTestClass
{
    [TestConstructorInterceptorA]
    public ConstructorInterceptorTestClass(string arg)
    {
    }
}
What gets compiled:
public ConstructorInterceptorTestClass(string arg)
{
    var values = new object[] { arg };
    var constructorInterceptor = new TestConstructorInterceptorA();
    constructorInterceptor.OnBeforeInitialization(typeof(ConstructorInterceptorTestClass), MethodBase.GetMethodFromHandle(methodof(ConstructorInterceptorTestClass..ctor()).MethodHandle, typeof(ConstructorInterceptorTestClass).TypeHandle), values);
    base..ctor();
    try
    {
           constructorInterceptor.OnEnter(typeof(ConstructorInterceptorTestClass), this, MethodBase.GetMethodFromHandle(methodof(ConstructorInterceptorTestClass..ctor()).MethodHandle, typeof(ConstructorInterceptorTestClass).TypeHandle), values);
    }
    catch (Exception e)
    {
           if(constructorInterceptor.OnException(e))
           {
               throw;
           }
    }
    finally
    {
           constructorInterceptor.OnExit();
    }
}
See Also