Code of this article and example of using RealProxy
with unit tests for both can be found on GitHub or downloaded from the link above.
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 object should not have to know anything about advice. AOP allows to separate cross-cutting concerns and makes it easier to follow Single Responsibility Principle (one of the SOLID principles). Logging, security, transactions and exceptions handling are the most common examples of using AOP. If you are not familiar with this programming technique, you can read this or this. It could be very useful because this article is 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 RealProxy
class to implement AOP. You can find some examples how to do it:
Example1: Aspect-Oriented Programming: Aspect-Oriented Programming with the RealProxy Class
This article also contains a lot of explanation about what is AOP, how 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 limitation: 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 an article about it.
Example3: Aspect Oriented Programming in C# with RealProxy.
Unfortunately, .NET Core does not have RealProxy
class. There is DispatchProxy
class instead. Using of DispatchProxy
class is a bit different than using RealProxy
class. As far as there are not a lot of examples of using DispatchProxy
, this article be can also considered as one of these examples.
Let’s implement logging using DispatchProxy
class.
Solution
Extension to Log Exception (Extensions.cs)
using System;
using System.Text;
namespace AOP
{
public static class Extensions
{
public static string GetDescription(this Exception e)
{
var builder = new StringBuilder();
AddException(builder, e);
return builder.ToString();
}
private static void AddException(StringBuilder builder, Exception e)
{
builder.AppendLine($"Message: {e.Message}");
builder.AppendLine($"Stack Trace: {e.StackTrace}");
if (e.InnerException != null)
{
builder.AppendLine("Inner Exception");
AddException(builder, e.InnerException);
}
}
}
}
Logging Advice (LoggingAdvice.cs)
public class LoggingAdvice<T> : DispatchProxy
{
private T _decorated;
private Action<string> _logInfo;
private Action<string> _logError;
private Func<object, string> _serializeFunction;
private TaskScheduler _loggingScheduler;
protected override object Invoke(MethodInfo targetMethod, object[] args)
{
if (targetMethod != null)
{
try
{
try
{
LogBefore(targetMethod, args);
}
catch (Exception ex)
{
LogException(ex);
}
var result = targetMethod.Invoke(_decorated, args);
var resultTask = result as Task;
if (resultTask != null)
{
resultTask.ContinueWith(task =>
{
if (task.Exception != null)
{
LogException(task.Exception.InnerException ?? task.Exception,
targetMethod);
}
else
{
object taskResult = null;
if (task.GetType().GetTypeInfo().IsGenericType &&
task.GetType().GetGenericTypeDefinition() == typeof(Task<>))
{
var property = task.GetType().GetTypeInfo().GetProperties()
.FirstOrDefault(p => p.Name == "Result");
if (property != null)
{
taskResult = property.GetValue(task);
}
}
LogAfter(targetMethod, args, taskResult);
}
},
_loggingScheduler);
}
else
{
try
{
LogAfter(targetMethod, args, result);
}
catch (Exception ex)
{
LogException(ex);
}
}
return result;
}
catch (Exception ex)
{
if (ex is TargetInvocationException)
{
LogException(ex.InnerException ?? ex, targetMethod);
throw ex.InnerException ?? ex;
}
}
}
throw new ArgumentException(nameof(targetMethod));
}
public static T Create(T decorated, Action<string> logInfo, Action<string> logError,
Func<object, string> serializeFunction, TaskScheduler loggingScheduler = null)
{
object proxy = Create<T, LoggingAdvice<T>>();
((LoggingAdvice<T>)proxy).SetParameters(decorated, logInfo, logError,
serializeFunction, loggingScheduler);
return (T)proxy;
}
private void SetParameters(T decorated, Action<string> logInfo, Action<string> logError,
Func<object, string> serializeFunction, TaskScheduler loggingScheduler)
{
if (decorated == null)
{
throw new ArgumentNullException(nameof(decorated));
}
_decorated = decorated;
_logInfo = logInfo;
_logError = logError;
_serializeFunction = serializeFunction;
_loggingScheduler = loggingScheduler ?? TaskScheduler.FromCurrentSynchronizationContext();
}
private string GetStringValue(object obj)
{
if (obj == null)
{
return "null";
}
if (obj.GetType().GetTypeInfo().IsPrimitive || obj.GetType().GetTypeInfo().IsEnum ||
obj is string)
{
return obj.ToString();
}
try
{
return _serializeFunction?.Invoke(obj) ?? obj.ToString();
}
catch
{
return obj.ToString();
}
}
private void LogException(Exception exception, MethodInfo methodInfo = null)
{
try
{
var errorMessage = new StringBuilder();
errorMessage.AppendLine($"Class {_decorated.GetType().FullName}");
errorMessage.AppendLine($"Method {methodInfo?.Name} threw exception");
errorMessage.AppendLine(exception.GetDescription());
_logError?.Invoke(errorMessage.ToString());
}
catch (Exception)
{
}
}
private void LogAfter(MethodInfo methodInfo, object[] args, object result)
{
var afterMessage = new StringBuilder();
afterMessage.AppendLine($"Class {_decorated.GetType().FullName}");
afterMessage.AppendLine($"Method {methodInfo.Name} executed");
afterMessage.AppendLine("Output:");
afterMessage.AppendLine(GetStringValue(result));
var parameters = methodInfo.GetParameters();
if (parameters.Any())
{
afterMessage.AppendLine("Parameters:");
for (var i = 0; i < parameters.Length; i++)
{
var parameter = parameters[i];
var arg = args[i];
afterMessage.AppendLine($"{parameter.Name}:{GetStringValue(arg)}");
}
}
_logInfo?.Invoke(afterMessage.ToString());
}
private void LogBefore(MethodInfo methodInfo, object[] args)
{
var beforeMessage = new StringBuilder();
beforeMessage.AppendLine($"Class {_decorated.GetType().FullName}");
beforeMessage.AppendLine($"Method {methodInfo.Name} executing");
var parameters = methodInfo.GetParameters();
if (parameters.Any())
{
beforeMessage.AppendLine("Parameters:");
for (var i = 0; i < parameters.Length; i++)
{
var parameter = parameters[i];
var arg = args[i];
beforeMessage.AppendLine($"{parameter.Name}:{GetStringValue(arg)}");
}
}
_logInfo?.Invoke(beforeMessage.ToString());
}
}
Let’s assume that we have an interface and a class.
public interface IMyClass
{
int MyMethod(string param);
}
public class MyClass: IMyClass
{
public int MyMethod(string param)
{
return param.Length;
}
}
To decorate MyClass
by LoggingAdvice
, we should do the following:
var decorated = LoggingAdvice<IMyClass>.Create(
new MyClass(),
s => Debug.WriteLine("Info:" + s),
s => Debug.WriteLine("Error:" + s),
o => o?.ToString());
To understand how it works, we call MyMesthod
of decorated
instance.
var length = decorated.MyMethod("Hello world!");
This line of code does:
decorated.MyMethod("Hello world!")
calls Invoke
method of LoggingAdvice
with targetMethod
equal to MyMethod
and args
equal to array with one element equal to "Hello world!
". Invoke
method of LoggingAdvice
class logs MyMethod
method name and input parameters (LogBefore
). Invoke
method of LoggingAdvice
class calls MyMethod
method of MyClass
. - If method call is succeeded, output parameters and result are logged (
LogAfter
) and Invoke
method returns result. - If method call throws an exception, the exception is logged (
LogException
) and Invoke
throws the same exception. - Result of the
Invoke
method execution (result or exception) returns as a result of calling MyMethod
of decorated
object.
Example
Let's assume that we are going to implement calculator which adds and subtracts integer numbers.
public interface ICalculator
{
int Add(int a, int b);
int Subtract(int a, int b);
}
public class Calculator : ICalculator
{
public int Add(int a, int b)
{
return a + b;
}
public int Subtract(int a, int b)
{
return a - b;
}
}
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.
public class CalculatorWithoutAop: ICalculator
{
private readonly ILogger _logger;
public CalculatorWithoutAop(ILogger logger)
{
_logger = logger;
}
public int Add(int a, int b)
{
_logger.Log($"Adding {a} + {b}");
var result = a + b;
_logger.Log($"Result is {result}");
return result;
}
public int Subtract(int a, int b)
{
_logger.Log($"Subtracting {a} - {b}");
var result = a - b;
_logger.Log($"Result is {result}");
return result;
}
}
There are 3 problems with this solution.
Calculator
class coupled with logging. Loosely coupled (because ILogger
it is an interface), but coupled. Every time you make changes in ILogger
interface, it affects Calculator
. - Code become more complex.
- It breaks Single Responsibility principle. Add function doesn't just add numbers. It logs input values, add values and logs result. The same for
Subtract
.
Code in this article allows you not to touch Calculator
class at all.
You just need to change creation of the class.
public class CalculatorFactory
{
private readonly ILogger _logger;
public CalculatorFactory(ILogger logger)
{
_logger = logger;
}
public ICalculator CreateCalculator()
{
return LoggingAdvice<ICalculator >.Create(
new Calculator(),
s => _logger.Log("Info:" + s),
s => _logger.Log("Error:" + s),
o => o?.ToString());
}
}
Conclusion
This code works in my cases. If you have any examples when this code does not work, or you have ideas how this code could be improved – feel free to contact me in any way.
That's it — enjoy!