Skip to content

Instantly share code, notes, and snippets.

@CarterTsai
Last active February 14, 2020 23:23
Show Gist options
  • Save CarterTsai/33702223eaca08e48b878abc050cae1a to your computer and use it in GitHub Desktop.
Save CarterTsai/33702223eaca08e48b878abc050cae1a to your computer and use it in GitHub Desktop.
aop sample
using System;
using System.Reflection;
using System.Text.Json;
namespace Sample.AOPProxy
{
public class LoggerDecorator<T> : DispatchProxy
{
private T _decorated;
public static T Create(T decorated)
{
object proxy = Create<T, LoggerDecorator<T>>();
((LoggerDecorator<T>)proxy).SetParameters(decorated);
return (T)proxy;
}
private void SetParameters(T decorated)
{
if (decorated == null)
{
throw new ArgumentNullException(nameof(decorated));
}
_decorated = decorated;
}
protected override object Invoke(MethodInfo targetMethod, object[] args)
{
try
{
LogBefore(targetMethod, args);
var result = targetMethod.Invoke(_decorated, args);
LogAfter(targetMethod, args, result);
return result;
}
catch (Exception ex) when (ex is TargetInvocationException)
{
LogException(ex.InnerException ?? ex, targetMethod);
throw ex.InnerException ?? ex;
}
}
private void LogException(Exception exception, MethodInfo methodInfo = null)
{
Console.WriteLine($"LogException: Class {_decorated.GetType().FullName}, Method {methodInfo.Name} throw exception:\n{exception}");
}
private void LogAfter(MethodInfo methodInfo, object[] args, object result)
{
Console.WriteLine($@"Executing LogAfter : Class: {_decorated.GetType().FullName}, Method {methodInfo.Name}, Args: {JsonSerializer.Serialize(args)}, Result: {JsonSerializer.Serialize(result)}");
}
private void LogBefore(MethodInfo methodInfo, object[] args)
{
Console.WriteLine($@"Executing LogBefore: Class: { methodInfo.GetType().FullName}, Method :{methodInfo.Name}, Args: {JsonSerializer.Serialize(args)}");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment