IMethodInterceptor
NexusLabs.Needlr¶
NexusLabs.Needlr¶
IMethodInterceptor Interface¶
Intercepts method invocations on a service. Implement this interface to create reusable cross-cutting concerns like logging, caching, or timing.
Example¶
public class LoggingInterceptor : IMethodInterceptor
{
private readonly ILogger _logger;
public LoggingInterceptor(ILogger logger) => _logger = logger;
public async ValueTask<object?> InterceptAsync(IMethodInvocation invocation)
{
_logger.LogInformation("Calling {Method}", invocation.Method.Name);
var sw = Stopwatch.StartNew();
try
{
var result = await invocation.ProceedAsync();
_logger.LogInformation("{Method} completed in {Elapsed}ms",
invocation.Method.Name, sw.ElapsedMilliseconds);
return result;
}
catch (Exception ex)
{
_logger.LogError(ex, "{Method} failed", invocation.Method.Name);
throw;
}
}
}
Remarks¶
Unlike decorators (which require implementing every method of an interface), interceptors handle any method invocation with a single implementation. Apply interceptors to services using InterceptAttribute<TInterceptor>.
Interceptors are resolved from the DI container and can have their own dependencies. They are automatically excluded from Needlr's auto-registration because they are internal infrastructure resolved by generated proxy classes, not by user code.
Methods¶
IMethodInterceptor.InterceptAsync(IMethodInvocation) Method¶
Called when an intercepted method is invoked. Call ProceedAsync() to continue to the next interceptor in the chain or to the actual method implementation.
System.Threading.Tasks.ValueTask<object?> InterceptAsync(NexusLabs.Needlr.IMethodInvocation invocation);
Parameters¶
invocation IMethodInvocation
Context about the method being invoked, including the target instance, method metadata, and arguments.
Returns¶
System.Threading.Tasks.ValueTask<System.Object>
The result of the method invocation (or the modified result if the
interceptor transforms it). For void methods, return null.