• Sun. Dec 29th, 2024

How to use DispatchProxy for AOP in .NET Core

Byadmin

Nov 14, 2024



public class CustomLogger : DispatchProxy where T : class
{
    private readonly ILogger _logger;
    private T target;
    protected override object Invoke
    (MethodInfo targetMethod, object[] args)
    {
       throw new NotImplementedException();
    }
    public static T Create(T target)
    {
       throw new NotImplementedException();
    }
}

The CustomLogger class shown in the preceding code uses Serilog to log data in this example. The following code snippet shows how you can update the Invoke method we created in the MyClassDispatchProxy class earlier to incorporate logging capabilities.

protected override object Invoke
    (MethodInfo targetMethod, object[] args)
    {
        if(targetMethod == null)
            throw new ArgumentNullException(nameof(targetMethod));
        _logger.Information($”Entering method: {targetMethod.Name}…”);
         var result = targetMethod.Invoke(target, args);
        _logger.Information($”Exiting method: {targetMethod.Name}…”);
        return result;
    }

Note how the method calls are logged before and after invocation in the Invoke method. If the targetMethod instance is null, the Invoke method throws an exception. In the Create method, we create a new instance of the CustomLogger class and then set the target object based on which the proxy object will intercept method calls.



Source link