Saturday, November 23, 2024

How you can use DispatchProxy for AOP in .NET Core


public class CustomLogger : DispatchProxy the place T : class
{
    non-public readonly ILogger _logger;
    non-public T goal;
    protected override object Invoke
    (MethodInfo targetMethod, object[] args)
    {
       throw new NotImplementedException();
    }
    public static T Create(T goal)
    {
       throw new NotImplementedException();
    }
}

The CustomLogger class proven within the previous code makes use of Serilog to log knowledge on this instance. The next code snippet exhibits how one can replace the Invoke technique we created within the MyClassDispatchProxy class earlier to include logging capabilities.


protected override object Invoke
    (MethodInfo targetMethod, object[] args)
    {
        if(targetMethod == null)
            throw new ArgumentNullException(nameof(targetMethod));
        _logger.Info($"Getting into technique: {targetMethod.Identify}...");
         var end result = targetMethod.Invoke(goal, args);
        _logger.Info($"Exiting technique: {targetMethod.Identify}...");
        return end result;
    }

Notice how the tactic calls are logged earlier than and after invocation within the Invoke technique. If the targetMethod occasion is null, the Invoke technique throws an exception. Within the Create technique, we create a brand new occasion of the CustomLogger<T> class after which set the goal object based mostly on which the proxy object will intercept technique calls.

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles