Skip to content

CustomInterceptors

Alexei Stryker edited this page Jun 27, 2018 · 1 revision

Custom interceptors makes it possible to easily define simple interceptors in your project. To enable this feature you can either create a folder named Interceptors in the root directory of your project or define a custom location with CustomInterceptors.

Creating your first custom interceptor

Create a new .csx file in the Interceptors folder.
Use the following template:

using System;
using System.Text;
using System.Linq;
using System.Diagnostics;
using Cauldron.Interception.Cecilator;
using Cauldron.Interception.Fody;
using Cauldron.Interception.Fody.HelperTypes;
using Cauldron.Interception.Cecilator.Coders;

public static class CustomInterceptor
{
    // Optional
    public static string Name = "The name of the script";
    // Optional
    // This defines the order of the script execution in case there are
    // multiple scripts in place. Default is int.MaxValue.
    // The higher the value the lesser the priority.
    public static int Priority = 120;

    [Display("The name of the interceptor")] // Optional
    public static void Interceptor1(Builder builder)
    {
    }

    [Display("The name of the interceptor")] // Optional
    public static void Interceptor2(Builder builder)
    {
    }
}

Upon build, Cauldron compiles the script to an assembly and executes all interceptors in the script.

The following sample script adds a Console.WriteLine to all methods with a name that ends with Test in your project.

        var consoleType = builder.GetType("System.Console");
        var writeLineMethod = consoleType.GetMethod("WriteLine", true, BuilderTypes.String.BuilderType).Import();

        foreach (var method in builder
            .GetTypes(SearchContext.Module_NoGenerated)
            .SelectMany(x => x.GetMethods())
            .Where(x => !x.IsAbstract && x.Name.EndsWith("Test")))
        {
            builder.Log(LogTypes.Info, $"Implementing interceptor for method {method.Name}");
            method.NewCoder()
                .Call(writeLineMethod, method.Name).End
                .Insert(InsertionPosition.Beginning);
        }

See also Cecilator

Known bugs

The current version does not detect changes in the .csx file correctly.