🎯 Key Takeaways: C# 12+ interceptors let you replace method calls at compile time. Perfect for logging, caching, and AOP scenarios without runtime overhead.
Want to intercept method calls without reflection or runtime overhead? Interceptors are the compile-time solution!
🚀 What Are Interceptors?
// ✅ Your original method
public class OrderService
{
public async Task<Order> GetOrderAsync(int id)
{
// Database call
return await _context.Orders.FindAsync(id);
}
}
// ✅ Interceptor that replaces the method call
using System.Runtime.InteropServices;
[InterceptsLocation(
filePath: "OrderService.cs",
line: 42,
character: 13)]
public static async Task<Order> GetOrderWithCacheAsync(this OrderService service, int id)
{
// ✅ Check cache first
var cacheKey = $"order:{id}";
var cached = await _cache.GetStringAsync(cacheKey);
if (cached != null)
{
return JsonSerializer.Deserialize<Order>(cached);
}
// ✅ Call original method
var order = await service.GetOrderAsync(id);
// ✅ Cache result
await _cache.SetStringAsync(cacheKey, JsonSerializer.Serialize(order));
return order;
}
// Usage - Call is automatically intercepted!
var order = await _orderService.GetOrderAsync(123);
// ✅ Actually calls GetOrderWithCacheAsync!
💡 Real-World: Logging Interceptor
// ✅ Logging interceptor
[InterceptsLocation("ProductService.cs", 15, 9)]
public static async Task<T> LogAndExecute<T>(this object target, Func<Task<T>> method, string methodName)
{
var logger = ServiceProvider.GetService<ILogger>();
var stopwatch = Stopwatch.StartNew();
logger.LogInformation("Starting {MethodName}", methodName);
try
{
var result = await method();
stopwatch.Stop();
logger.LogInformation("Completed {MethodName} in {Duration}ms",
methodName, stopwatch.ElapsedMilliseconds);
return result;
}
catch (Exception ex)
{
logger.LogError(ex, "Failed {MethodName}", methodName);
throw;
}
}
// Automatically intercepts method calls with logging!
public async Task<Product> GetProductAsync(int id)
{
// Intercepted with logging!
return await _context.Products.FindAsync(id);
}
📊 Interceptor Benefits
| Feature | Reflection | Interceptors |
|---|---|---|
| Performance | ❌ Slow | ✅ Zero overhead |
| Compile-time Safety | ❌ Runtime errors | ✅ Compile-time checked |
| Debugging | ❌ Hard to follow | ✅ Easy to debug |
| Use Cases | Dynamic scenarios | AOP, caching, logging |
💡 Pro Tip: Source Generator + Interceptor
// ✅ Combine with Source Generators
[Generator]
public class InterceptorGenerator : ISourceGenerator
{
public void Execute(GeneratorExecutionContext context)
{
// Generate interceptor attributes automatically
var source = @"
using System.Runtime.InteropServices;
namespace MyApp.Interceptors
{
[AttributeUsage(AttributeTargets.Method)]
public class InterceptAttribute : Attribute
{
public InterceptAttribute(string filePath, int line, int character)
{
FilePath = filePath;
Line = line;
Character = character;
}
public string FilePath { get; }
public int Line { get; }
public int Character { get; }
}
}";
context.AddSource("InterceptAttribute.g.cs", source);
}
public void Initialize(GeneratorInitializationContext context) { }
}

