Skip to content

Method interception

SERKAN edited this page Oct 6, 2020 · 1 revision
public class LogAttribute: MethodInterceptorAttribute
{
}

// You must specify the attribute type for the interceptor.

[InterceptFor(typeof(LogAttribute))]
public class LogInterceptor: MethodInterceptor
{
    private readonly Logger logger;

    // The Logger dependency will be resolved using Microsoft's DI container
    public LogInterceptor(Logger logger)
    {
        this.logger = logger;
    }

    // MethodInterceptor class provides OnBefore, OnAfter and OnError methods.
    // You can override these methods to seperate the logic you don't want in your actual method.
    public override Task OnBefore(IInvocation invocation)
    {
        logger.LogInfo($"[Log] Executing method: {invocation.TargetType.FullName}.{invocation.Method.Name}");

        return Task.FromResult(Task.CompletedTask);
    }
}
Clone this wiki locally