Tech
How to 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 methodology 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.Data($"Coming into methodology: {targetMethod.Identify}...");
var outcome = targetMethod.Invoke(goal, args);
_logger.Data($"Exiting methodology: {targetMethod.Identify}...");
return outcome;
}
Notice how the tactic calls are logged earlier than and after invocation within the Invoke methodology. If the targetMethod occasion is null, the Invoke methodology throws an exception. Within the Create methodology, we create a brand new occasion of the CustomLogger