Intercept Calls to Any Method

An override aspect changes a method for every caller, and it needs the method’s source code. An interceptor changes the calls to a method instead: an aspect or a fabric selects the calls in the code you choose, and Metalama rewrites them at build time to target the interceptor. The called method can belong to any assembly: the .NET libraries, a NuGet package, or another team’s project.

Benefits

  • Reach any method. The intercepted method can be static, sealed, non-virtual, an extension method or a struct method, in any assembly. You need neither its source code, nor an interface, nor dependency injection.
  • Choose the callers. A registration applies to the target type of an aspect, a namespace, a project, the types a query selects, some build configurations only, or every project that references a library.
  • One template for a whole API. A T# template generates one interceptor per intercepted signature, including async, iterator and generic methods. You can also redirect calls to a plain C# method that you debug and unit-test like any other code.
  • Know the caller. The interceptor can receive the calling member, the calling object, a parameter of the calling method, and the caller information attributes resolved to the intercepted call.
  • Easy to add and to remove. The business code does not change. Deleting the registration removes the interceptor.

Example

ShippingClient is a class of a vendor SDK. Its methods sometimes throw a TimeoutException, and the application calls them from many places. The following fabric retries the calls to its methods whose name starts with Get:

internal class Fabric : ProjectFabric
{
    public override void AmendProject( IProjectAmender amender )
        => amender.InterceptMethods(
            calls => calls
                .Type( typeof(ShippingClient) )
                .AllMethods()
                .Where( m => m.Name.StartsWith( "Get" ) )
                .RedirectToSynthesizedMethod( nameof(this.Retry) )
                .WithArgs( new { maxAttempts = 3 } ) );

    [Template]
    public dynamic? Retry( [CompileTime] int maxAttempts )
    {
        for ( var attempt = 1;; attempt++ )
        {
            try
            {
                return meta.Proceed();
            }
            catch ( TimeoutException e ) when ( attempt < maxAttempts )
            {
                Console.WriteLine( $"Attempt {attempt} failed: {e.Message} Retrying." );
            }
        }
    }
}

From this template, Metalama generates one interceptor per intercepted method, and routes the matching calls to it. The source code of the callers is unchanged. CreateShipment is not intercepted, because retrying an operation that is not idempotent could create the shipment twice.

What interceptors are good at

  • Enforcing a policy on every call to an API, now and in the code written next year: telemetry, an audit trail of calls to sensitive APIs, retries around a third-party service.
  • Changing legacy code safely. An interceptor is a seam at every call site: you can replace a hard-wired dependency with a fake, record real interactions, and route the calls to a new implementation one module at a time, before you edit any call site.
  • Changing behavior in some builds only. One file traces the calls to a library in a diagnostic build, injects failures in a test build, or disables e-mails in a staging build.
  • Migrating from PostSharp. Metalama aspects cannot modify the methods of other assemblies. Interceptors provide the call-site interception that PostSharp users rely on.

When to use something else

Interceptors are a poor fit for some problems, and the documentation says which tool to use instead:

  • To generate optimized code from the arguments of each call, such as a lambda, a query or a SQL string, write a Roslyn source generator with C# interceptors. Metalama interceptors are unrelated to that C# feature.
  • To change a method you own for every caller, use an override aspect.
  • For a one-time change, such as moving off an obsolete API, use a code fix or a refactoring, so the change is visible in the source code.
  • Calls outside your source code, made by a library, the framework, reflection or dynamic, cannot be intercepted at build time.
  • Property accesses, constructor calls, operators and await expressions are not intercepted.

Commented examples

Availability

Interceptors ship with Metalama 2027.0, in the Metalama.Extensions.Interceptors package, which works with a free Metalama Community license.

Resources