Skip to content
  • Home
  • About
  • No Access
  • Privacy Policy
Bits of .NET
Bits of .NET
  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy

Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy
C#

C# Interceptors: Intercept Method Calls Like a Pro

- 23.08.26 - ErcanOPAK

🎯 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) { }
}

Related posts:

Define a Default Value when insert New Record From ASPxGridView

Define a Default Value when insert New Record From ASPxGridView

C#: Use Partial Classes to Split Code Across Files

C#: Use Partial Classes to Split Code Across Files

C#: Fix a Flags Enum That Silently Produces an Invalid Combination Because One of Its Values Isn't a...

C#: Fix a Flags Enum That Silently Produces an Invalid Combination Because One of Its Values Isn't a...

Views: 27

Post navigation

C# 13 in Practice: Real-World Use Cases for Every New Feature
API Response Compression in .NET: 90% Smaller Payloads

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

November 2026
M T W T F S S
 1
2345678
9101112131415
16171819202122
23242526272829
30  
« Oct    

Most Viewed Posts

  • How to make theater mode the default for Youtube (1,068)
  • Get the User Name and Domain Name from an Email Address in SQL (990)
  • How to add default value for Entity Framework migrations for DateTime and Bool (986)
  • Get the First and Last Word from a String or Sentence in SQL (865)
  • How to select distinct rows in a datatable in C# (859)
  • How to enable, disable and check if Service Broker is enabled on a database in SQL Server (661)
  • Add Constraint to SQL Table to ensure email contains @ (619)
  • Average of all values in a column that are not zero in SQL (577)
  • How to use Map Mode for Vertical Scroll Mode in Visual Studio (553)
  • Find numbers with more than two decimal places in SQL (481)

Recent Posts

  • Network Speed Monitor Windows Application v2.5.1
  • Ağ Hızı İzleyici Windows Uygulaması v2.5.1
  • How to make theater mode the default for Youtube
  • The AI Prompt That Audits a Function for Thread-Safety Gaps
  • Ajax: Fix a Fetch Request Caching a Response Despite No-Store
  • WordPress: Fix a Navigation Block Losing Submenu Items After Sync
  • Visual Studio: Fix CodeLens Reference Counts Stuck at Stale Numbers
  • C#: Fix a UTF-8 String Literal Behaving Differently in a Switch
  • Photoshop: Fix a Liquify Mesh Snapping Back on a Smart Object
  • The AI Prompt That Turns a Crash Dump Into a Short Repro Script

Most Viewed Posts

  • How to make theater mode the default for Youtube (1,068)
  • Get the User Name and Domain Name from an Email Address in SQL (990)
  • How to add default value for Entity Framework migrations for DateTime and Bool (986)
  • Get the First and Last Word from a String or Sentence in SQL (865)
  • How to select distinct rows in a datatable in C# (859)

Recent Posts

  • Network Speed Monitor Windows Application v2.5.1
  • Ağ Hızı İzleyici Windows Uygulaması v2.5.1
  • How to make theater mode the default for Youtube
  • The AI Prompt That Audits a Function for Thread-Safety Gaps
  • Ajax: Fix a Fetch Request Caching a Response Despite No-Store

Social

  • ErcanOPAK.com
  • GoodReads
  • LetterBoxD
  • Linkedin
  • The Blog
  • Twitter
© 2026 Bits of .NET | Built with Xblog Plus free WordPress theme by wpthemespace.com