[Home](../../) › [Metalama](../../metalama) › [Features](../features.md) › [Core Features](core.md) › [Code Generation](code-generation.md) › Intercept Calls to Any Method

# Intercept Calls to Any Method

> Metalama interceptors change the calls to a method in the code you select, at build time, even when the method belongs to the .NET libraries, a NuGet package, or another team's project.

Canonical: https://postsharp.net/metalama/features/interceptors

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`:

```csharp
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](https://postsharp.net/metalama/features/override).
* 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

* [Tracing calls](https://doc.postsharp.net/metalama/preview/src/call-tracing): trace the calls to a library from one file, or only in a trace build.
* [Auditing and monitoring calls](https://doc.postsharp.net/metalama/preview/src/call-telemetry): audit the calls to sensitive APIs, and produce trace spans and metrics for the calls to a third-party SDK.
* [Getting legacy code under test](https://doc.postsharp.net/metalama/preview/src/legacy-testing): replace hard-wired dependencies with fakes, then record and replay real interactions in characterization tests.
* [Replacing an implementation](https://doc.postsharp.net/metalama/preview/src/legacy-replacement): find which calls are used, compare the new implementation with the old one, and switch one module at a time.
* [Universal interceptor](https://doc.postsharp.net/metalama/preview/src/universal-interceptor): route the calls to a whole third-party API, with different signatures, through one run-time object.
* [Retrying calls to code you don't own](https://doc.postsharp.net/metalama/preview/src/exception-handling/retry/retry-6).

## Availability

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

## Resources

* Reference documentation: [Interceptors](https://doc.postsharp.net/metalama/preview/conceptual/interceptors)
* [When to use interceptors](https://doc.postsharp.net/metalama/preview/conceptual/interceptors/use-cases): use cases, limitations, and a comparison with other techniques.
* Blog post: [Intercepting Calls to Any Method with Metalama Interceptors](https://postsharp.net/blog/metalama-interceptors)

---

## Site navigation

- Previous: [Enhance Hand-Written Code](override.md)
- Next: [Reference Generated Code](reference-from-source-code.md)
- Index of the whole site: [llms.txt](../../llms.txt)

