Skip to content

Instantly share code, notes, and snippets.

@NikitaChizhov
Created February 11, 2020 20:55
Show Gist options
  • Save NikitaChizhov/f8feb90df53d8920cee1e0a3946877dd to your computer and use it in GitHub Desktop.
Save NikitaChizhov/f8feb90df53d8920cee1e0a3946877dd to your computer and use it in GitHub Desktop.
internal class DispatchProxyMinimalLoggingDecorator<TDecorated> : DispatchProxy
{
private TDecorated _decorated;
private ILogger<DispatchProxyLoggingDecorator<TDecorated>> _logger;
protected override object Invoke(MethodInfo targetMethod, object[] args)
{
try
{
_logger.LogInformation("Logging something before invoking {decoratedClass}.{methodName}",
typeof(TDecorated), targetMethod.Name);
var result = targetMethod.Invoke(_decorated, args);
_logger.LogInformation("Logging something after method {decoratedClass}.{methodName} completion.",
typeof(TDecorated), targetMethod.Name);
return result;
}
catch (TargetInvocationException ex)
{
_logger.LogError(ex.InnerException ?? ex,
"Error during invocation of {decoratedClass}.{methodName}",
typeof(TDecorated), targetMethod.Name);
throw ex.InnerException ?? ex;
}
}
public static TDecorated Create(TDecorated decorated, ILogger<DispatchProxyLoggingDecorator<TDecorated>> logger)
{
object proxy = Create<TDecorated, DispatchProxyLoggingDecorator<TDecorated>>();
((DispatchProxyLoggingDecorator<TDecorated>)proxy).SetParameters(decorated, logger);
return (TDecorated)proxy;
}
private void SetParameters(TDecorated decorated, ILogger<DispatchProxyLoggingDecorator<TDecorated>> logger)
{
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
_decorated = decorated ?? throw new ArgumentNullException(nameof(decorated));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment