Junior — Middle
Can you explain what is meant by the interceptor concept in programming?
sobes.tech AI
Answer from AI
Interceptor is a programming pattern that allows intercepting method calls or message processing to add additional logic without changing the core code.
In C#, interceptors are often used in the context of aspect-oriented programming (AOP) or when working with proxy objects. For example, they can intercept method calls for logging, access rights verification, caching, or exception handling.
An example of using an interceptor with Castle DynamicProxy:
public class LoggingInterceptor : IInterceptor
{
public void Intercept(IInvocation invocation)
{
Console.WriteLine($"Method {invocation.Method.Name} call started");
invocation.Proceed(); // call the original method
Console.WriteLine($"Method {invocation.Method.Name} call finished");
}
}
// Creating a proxy with an interceptor
var proxyGenerator = new ProxyGenerator();
var myService = proxyGenerator.CreateInterfaceProxyWithTarget<IMyService>(new MyService(), new LoggingInterceptor());
myService.SomeMethod();
Thus, the interceptor allows injecting additional behavior around method calls without modifying their implementation.