Aspect Oriented Programming In C# Using DispatchProxy

Introduction

 
Aspect-Oriented Programming (AOP) is a very powerful approach to avoid boilerplate code and archive better modularity. The main idea is to add behavior (advice) to the existing code without making any changes in the code itself. AOP provides a way of weaving an aspect into the code. An aspect is supposed to be generic so it can be applied to any object and the object should not have to know anything about advice. AOP allows us to separate cross-cutting concerns and makes it easier to follow the Single Responsibility Principle (one of the SOLID principles). Logging, security, transactions, and exception handling are the most common examples of using AOP. If you are not familiar with this programming technique you can read this. It could be very useful because this article talks mostly about how to use AOP in C# rather than what AOP is. Don’t be scared if you still do not understand what it is all about. After looking at several examples, it becomes much easier to understand.
 
In Java, AOP is implemented in AspectJ and Spring frameworks. There are PostSharp (not free), NConcern, and some other frameworks (not very popular and easy to use) to do almost the same in . NET.
 
It is also possible to use the RealProxy class to implement AOP. You can find some examples of how to do it.
 
 
This article also contains a lot of explanations of what is AOP, how the Decorator Design Pattern works, and examples of implementing logging and authentication using AOP.
 
Example2
 
MSDN.
 
Unfortunately, these examples have some significant drawbacks. Example1 does not support out parameters. Example2 has a limitation: a decorated class should be inherited from MarshalByRefObject (it could be a problem if it is not class designed by you). Also, both examples do not support asynchronous functions as expected. Several months ago, I changed the first example to support Task results and output parameters and wrote article about it.
 
 
Unfortunately, .NETCore does not have a RealProxy class. There is DispatchProxy class instead. Using the DispatchProxy class is a bit different than using the RealProxy class.
 
Let’s implement logging using DispatchProxy class.
 
Code of these articles and examples of using RealProxy with unit tests for both can be found on GitHub.
 
Solution Extension to log exception (Extensions.cs)
  1. using System;  
  2. using System.Text;  
  3.   
  4. namespace AOP  
  5. {  
  6.     public static class Extensions  
  7.     {  
  8.         public static string GetDescription(this Exception e)  
  9.         {  
  10.             var builder = new StringBuilder();  
  11.   
  12.             AddException(builder, e);  
  13.   
  14.             return builder.ToString();  
  15.         }  
  16.   
  17.         private static void AddException(StringBuilder builder, Exception e)  
  18.         {  
  19.             builder.AppendLine($"Message: {e.Message}");  
  20.             builder.AppendLine($"Stack Trace: {e.StackTrace}");  
  21.   
  22.             if (e.InnerException != null)  
  23.             {  
  24.                 builder.AppendLine("Inner Exception");  
  25.                 AddException(builder, e.InnerException);  
  26.             }  
  27.         }  
  28.     }  
  29. }  
Logging Advice (LoggingAdvice.cs)
  1. public class LoggingAdvice<T> : DispatchProxy  
  2. {  
  3.     private T _decorated;  
  4.     private Action<string> _logInfo;  
  5.     private Action<string> _logError;  
  6.     private Func<objectstring> _serializeFunction;  
  7.     private TaskScheduler _loggingScheduler;  
  8.   
  9.     protected override object Invoke(MethodInfo targetMethod, object[] args)  
  10.     {  
  11.         if (targetMethod != null)  
  12.         {  
  13.             try  
  14.             {  
  15.                 try  
  16.                 {  
  17.                     LogBefore(targetMethod, args);  
  18.                 }  
  19.                 catch (Exception ex)  
  20.                 {  
  21.                     //Do not stop method execution if exception  
  22.                     LogException(ex);  
  23.                 }  
  24.   
  25.                 var result = targetMethod.Invoke(_decorated, args);  
  26.                 var resultTask = result as Task;  
  27.   
  28.                 if (resultTask != null)  
  29.                 {  
  30.                     resultTask.ContinueWith(task =>  
  31.                         {  
  32.                             if (task.Exception != null)  
  33.                             {  
  34.                                 LogException(task.Exception.InnerException ?? task.Exception, targetMethod);  
  35.                             }  
  36.                             else  
  37.                             {  
  38.                                 object taskResult = null;  
  39.                                 if (task.GetType().GetTypeInfo().IsGenericType &&  
  40.                                     task.GetType().GetGenericTypeDefinition() == typeof(Task<>))  
  41.                                 {  
  42.                                     var property = task.GetType().GetTypeInfo().GetProperties()  
  43.                                         .FirstOrDefault(p => p.Name == "Result");  
  44.                                     if (property != null)  
  45.                                     {  
  46.                                         taskResult = property.GetValue(task);  
  47.                                     }  
  48.                                 }  
  49.   
  50.                                 LogAfter(targetMethod, args, taskResult);  
  51.                             }  
  52.                         },  
  53.                         _loggingScheduler);  
  54.                 }  
  55.                 else  
  56.                 {  
  57.                     try  
  58.                     {  
  59.                         LogAfter(targetMethod, args, result);  
  60.                     }  
  61.                     catch (Exception ex)  
  62.                     {  
  63.                         //Do not stop method execution if an exception  
  64.                         LogException(ex);  
  65.                     }  
  66.                 }  
  67.   
  68.                 return result;  
  69.             }  
  70.             catch (Exception ex)  
  71.             {  
  72.                 if (ex is TargetInvocationException)  
  73.                 {  
  74.                     LogException(ex.InnerException ?? ex, targetMethod);  
  75.                     throw ex.InnerException ?? ex;  
  76.                 }  
  77.             }  
  78.         }  
  79.   
  80.         throw new ArgumentException(nameof(targetMethod));  
  81.     }  
  82.   
  83.     public static T Create(T decorated, Action<string> logInfo, Action<string> logError,  
  84.         Func<objectstring> serializeFunction, TaskScheduler loggingScheduler = null)  
  85.     {  
  86.         object proxy = Create<T, LoggingAdvice<T>>();  
  87.         ((LoggingAdvice<T>)proxy).SetParameters(decorated, logInfo, logError, serializeFunction, loggingScheduler);  
  88.   
  89.         return (T)proxy;  
  90.     }  
  91.   
  92.     private void SetParameters(T decorated, Action<string> logInfo, Action<string> logError,  
  93.         Func<objectstring> serializeFunction, TaskScheduler loggingScheduler)  
  94.     {  
  95.         if (decorated == null)  
  96.         {  
  97.             throw new ArgumentNullException(nameof(decorated));  
  98.         }  
  99.   
  100.         _decorated = decorated;  
  101.         _logInfo = logInfo;  
  102.         _logError = logError;  
  103.         _serializeFunction = serializeFunction;  
  104.         _loggingScheduler = loggingScheduler ?? TaskScheduler.FromCurrentSynchronizationContext();  
  105.     }  
  106.   
  107.     private string GetStringValue(object obj)  
  108.     {  
  109.         if (obj == null)  
  110.         {  
  111.             return "null";  
  112.         }  
  113.   
  114.         if (obj.GetType().GetTypeInfo().IsPrimitive || obj.GetType().GetTypeInfo().IsEnum || obj is string)  
  115.         {  
  116.             return obj.ToString();  
  117.         }  
  118.   
  119.         try  
  120.         {  
  121.             return _serializeFunction?.Invoke(obj) ?? obj.ToString();  
  122.         }  
  123.         catch  
  124.         {  
  125.             return obj.ToString();  
  126.         }  
  127.     }  
  128.   
  129.     private void LogException(Exception exception, MethodInfo methodInfo = null)  
  130.     {  
  131.         try  
  132.         {  
  133.             var errorMessage = new StringBuilder();  
  134.             errorMessage.AppendLine($"Class {_decorated.GetType().FullName}");  
  135.             errorMessage.AppendLine($"Method {methodInfo?.Name} threw exception");  
  136.             errorMessage.AppendLine(exception.GetDescription());  
  137.   
  138.             _logError?.Invoke(errorMessage.ToString());  
  139.         }  
  140.         catch (Exception)  
  141.         {  
  142.             // ignored  
  143.             //Method should return original exception  
  144.         }  
  145.     }  
  146.   
  147.     private void LogAfter(MethodInfo methodInfo, object[] args, object result)  
  148.     {  
  149.         var afterMessage = new StringBuilder();  
  150.         afterMessage.AppendLine($"Class {_decorated.GetType().FullName}");  
  151.         afterMessage.AppendLine($"Method {methodInfo.Name} executed");  
  152.         afterMessage.AppendLine("Output:");  
  153.         afterMessage.AppendLine(GetStringValue(result));  
  154.   
  155.         var parameters = methodInfo.GetParameters();  
  156.         if (parameters.Any())  
  157.         {  
  158.             afterMessage.AppendLine("Parameters:");  
  159.             for (var i = 0; i < parameters.Length; i++)  
  160.             {  
  161.                 var parameter = parameters[i];  
  162.                 var arg = args[i];  
  163.                 afterMessage.AppendLine($"{parameter.Name}:{GetStringValue(arg)}");  
  164.             }  
  165.         }  
  166.   
  167.         _logInfo?.Invoke(afterMessage.ToString());  
  168.     }  
  169.   
  170.     private void LogBefore(MethodInfo methodInfo, object[] args)  
  171.     {  
  172.         var beforeMessage = new StringBuilder();  
  173.         beforeMessage.AppendLine($"Class {_decorated.GetType().FullName}");  
  174.         beforeMessage.AppendLine($"Method {methodInfo.Name} executing");  
  175.         var parameters = methodInfo.GetParameters();  
  176.         if (parameters.Any())  
  177.         {  
  178.             beforeMessage.AppendLine("Parameters:");  
  179.   
  180.             for (var i = 0; i < parameters.Length; i++)  
  181.             {  
  182.                 var parameter = parameters[i];  
  183.                 var arg = args[i];  
  184.                 beforeMessage.AppendLine($"{parameter.Name}:{GetStringValue(arg)}");  
  185.             }  
  186.         }  
  187.   
  188.         _logInfo?.Invoke(beforeMessage.ToString());  
  189.     }  
  190. }  
Let’s assume that we have an interface and a class.
  1. public interface IMyClass  
  2. {  
  3.     int MyMethod(string param);  
  4. }  
  5.   
  6. public class MyClass  
  7. {  
  8.     public int MyMethod(string param)  
  9.     {  
  10.         return param.Length;  
  11.     }  
  12. }  
To decorate MyClass by LoggingAdvice, we should do the following.
  1. var decorated = LoggingAdvice<IMyClass>.Create(  
  2.                 new MyClass(),  
  3.                 s => Debug.WriteLine("Info:" + s),  
  4.                 s => Debug.WriteLine("Error:" + s),  
  5.                 o => o?.ToString());  
To understand how it works, we call MyMethod of decorated instance.
  1. var length = decorated.MyMethod("Hello world!");  
This line of code does,
  1. decorated.MyMethod("Hello world!") calls Invoke method of LoggingAdvice with targetMethod equal to MyMethod and args equal to an array with one element equal to "Hello world!".
  2. Invoke method of LoggingAdvice class logs MyMethod method name and input parameters (LogBefore).
  3. Invoke method of LoggingAdvice class calls MyMethod method of MyClass.
  4. If the method call succeeds output parameters and the result are logged (LogAfter) and the Invoke method returns the result.
  5. If method call throws an exception, the exception is logged (LogException), and Invoke throws the same exception.
  6. Result of the Invoke method execution (result or exception) returns as a result of calling MyMethod of decorated object.
Example
 
Let us assume that we are going to implement a calculator that adds and subtracts integer numbers.
  1. public interface ICalculator  
  2. {  
  3.     int Add(int a, int b);  
  4.     int Subtract(int a, int b);  
  5. }  
  6.   
  7. public class Calculator : ICalculator  
  8. {  
  9.     public int Add(int a, int b)  
  10.     {  
  11.         return a + b;  
  12.     }  
  13.   
  14.     public int Subtract(int a, int b)  
  15.     {  
  16.         return a - b;  
  17.     }  
  18. }  
It is easy. Each method has only one responsibility.
 
One day, some users start complaining that sometimes Add(2, 2) returns 5. You don’t understand what's going on and decide to add logging.
  1. public class CalculatorWithoutAop: ICalculator  
  2. {  
  3.     private readonly ILogger _logger;  
  4.   
  5.     public CalculatorWithoutAop(ILogger logger)  
  6.     {  
  7.         _logger = logger;  
  8.     }  
  9.   
  10.     public int Add(int a, int b)  
  11.     {  
  12.         _logger.Log($"Adding {a} + {b}");  
  13.         var result = a + b;  
  14.         _logger.Log($"Result is {result}");  
  15.   
  16.         return result;  
  17.     }  
  18.   
  19.     public int Subtract(int a, int b)  
  20.     {  
  21.         _logger.Log($"Subtracting {a} - {b}");  
  22.         var result = a - b;  
  23.         _logger.Log($"Result is {result}");  
  24.   
  25.         return result;  
  26.     }  
  27. }  
There are 3 problems with this solution.
  1. Calculator class is coupled with logging. Loosely coupled (because ILoger it is an interface), but coupled. Every time you make changes in the ILoger interface, it affects the Calculator.
  2. Code becomes more complex.
  3. It breaks the Single Responsibility Principle. Add function doesn't just add numbers. It logs input values, adds values, and logs results. The same for Subtract.
Code in this article allows you not to touch the Calculator class at all. You just need to change the creation of the class.
  1. public class CalculatorFactory  
  2. {  
  3.     private readonly ILogger _logger;  
  4.   
  5.     public CalculatorFactory(ILogger logger)  
  6.     {  
  7.         _logger = logger;  
  8.     }  
  9.   
  10.     public ICalculator CreateCalculator()  
  11.     {  
  12.         return LoggingAdvice<ICalculator >.Create(  
  13.             new Calculator(),  
  14.             s => _logger.Log("Info:" + s),  
  15.             s => _logger.Log("Error:" + s),  
  16.             o => o?.ToString());  
  17.     }  
  18. }  

Conclusion

 
This code works in my case. If you have any examples when this code does not work, or you have ideas on how this code could be improved – feel free to contact me.
That's it — enjoy!