Sobes.tech
Middle+

What is an interceptor?

sobes.tech AI

Answer from AI

Interceptor in C# is a mechanism that allows intercepting method calls, property accesses, and events of an object at runtime. It provides the ability to intervene in the standard execution process, add custom logic before or after the original method call, modify arguments or the return value.

Main features and areas of application:

  • Dynamic generation of proxy objects: Interceptors are often used together with libraries for dynamic proxy generation (e.g., Castle DynamicProxy, NProxy). The proxy object wraps the target object and intercepts all calls to it.
  • Aspect-oriented programming (AOP): Interceptors are a key mechanism for implementing AOP, allowing cross-cutting concerns (logging, caching, security, transaction handling) to be separated and applied to multiple objects without changing their source code.
  • Mocking and testing: Used for creating mock objects or stubs in unit tests, enabling the emulation of real dependencies' behavior.
  • Adding behavior at runtime: Allows adding or changing object behavior without modifying their source code or using inheritance.

Example implementation using Castle DynamicProxy (one of the popular frameworks):

  1. Defining the interceptor interface:

    // Interceptor interface
    public interface IInterceptor
    {
        void Intercept(IInvocation invocation);
    }
    
  2. Implementing the interceptor:

    // Example implementation of an interceptor for logging
    public class LoggingInterceptor : IInterceptor
    {
        public void Intercept(IInvocation invocation)
        {
            Console.WriteLine($"Method call: {invocation.Method.Name}");
    
            try
            {
                invocation.Proceed(); // Call the original method
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error in method {invocation.Method.Name}: {ex.Message}");
                throw;
            }
    
            Console.WriteLine($"Method {invocation.Method.Name} completed.");
        }
    }
    
  3. Applying the interceptor:

    // Using DynamicProxy to create a proxy object with an interceptor
    using Castle.DynamicProxy;
    
    // Target class example
    public class TargetClass
    {
        public virtual void SomeMethod(int value)
        {
            Console.WriteLine($"Inside TargetClass.SomeMethod with value: {value}");
        }
    }
    
    // Creating proxy generator and interceptor
    var generator = new ProxyGenerator();
    var interceptor = new LoggingInterceptor();
    
    // Creating a proxy object that intercepts calls to TargetClass
    var proxyObject = generator.CreateClassProxy<TargetClass>(interceptor);
    
    // Calling method via proxy object
    proxyObject.SomeMethod(123);
    

In this example, when proxyObject.SomeMethod(123) is called, control first passes to the Intercept method of the LoggingInterceptor. The interceptor performs logging before and after the original method call using invocation.Proceed().