Tags:CSharpAOPProgramming

What is an Interceptor?

A mechanism to modify or enhance method calls without changing the original code. Used for cross-cutting concerns (logging, caching, validation) via Aspect-Oriented Programming (AOP).

How It Works

  1. Proxy Objects: Libraries (e.g., Castle.DynamicProxy) generate proxy classes wrapping your objects.
  2. Intercept Calls: Inject logic before/after method execution.
  3. Common Workflow:
    • Pre-process (e.g., validate inputs).
    • Execute the original method.
    • Post-process (e.g., log results).

Example: Logging Interceptor

// Interceptor class
public class LoggingInterceptor : IInterceptor  
{  
    public void Intercept(IInvocation invocation)  
    {  
        Console.WriteLine($"START: {invocation.Method.Name}");  
        invocation.Proceed(); // Run the original method  
        Console.WriteLine($"END: {invocation.Method.Name}");  
    }  
}  
 
// Usage  
var proxy = new ProxyGenerator()  
    .CreateClassProxy<MyService>(new LoggingInterceptor());  
proxy.DoWork();  

Output:

START: DoWork  
Working...  
END: DoWork  

Use Cases

  • Logging: Track method calls/results.
  • Caching: Store results of expensive calls.
  • Validation: Check inputs before execution.
  • Retry Logic: Automatically retry failed operations.

Key Benefits

  • Separation of Concerns: Core logic stays clean.
  • Reusable: Apply to multiple methods/classes.
  • Non-Invasive: No changes to existing code.
  • Castle.DynamicProxy
  • PostSharp
  • Unity.Interception (for DI containers)