What are the advantages of using aspect orientated programming frameworks like postsharp over doing it manually? Thanks.
For a deep dive you can read Matthew D. Groves AOP in .NET: Pracitical Aspect-Oriented Programming.
Otherwise, the head guy at postsharp, Gael Fraiteur, is on SO from time to time, so he might also pop in here.
At it's core AOP is about seperating out 'cross cutting concerns' from your main logic. Things like logging, transaction management, etc are used throughout an application, but the code is not specific to a given class and is used repetitiously. AOP allows you to brake this code out of your classes and stick them elsewhere.
From https://blog.safaribooksonline.com/2013/07/17/why-you-should-be-using-aspect-oriented-programming/:
using System.Linq;
public class StringReverser
{
IMyLogger _log;
public StringReverser(IMyLogger logger)
{
_log = logger;
}
public string Reverse(string text)
{
_log.WriteLine("MyFunction: " + DateTime.Now);
_log.WriteLine("text (string) argument: " + text);
string result = null;
if (text != null)
result = new string(text.Reverse().ToArray());
_log.WriteLine("Return value: " + result);
return result;
}
}
The logging code has nothing to do with Reverse
and clutters up the code that actually gets work done. AOP allows you to move that code to a separate place:
public class StringReverser : IStringReverser
{
[LoggingAspect]
public string Reverse(string text)
{
if (text == null)
return null;
return new string(text.Reverse().ToArray());
}
}
And the logging code:
[Serializable]
public class LoggingAspect : MethodInterceptionAspect
{
IMyLogger _log;
public override void RuntimeInitialize(MethodBase method)
{
_log = MyServiceLocator.Get();
}
public override void OnInvoke(MethodInterceptionArgs args)
{
var methodName = args.Method.Name;
var parameters = args.Method.GetParameters();
_log.WriteLine(string.Format("{0} timestamp: {1}", methodName,
DateTime.Now));
for (var i = 0; i < args.Arguments.Count; i++)
_log.WriteLine(string.Format("{0} argument #{1}, {2} ({3}): {4}",
methodName,
i,
parameters[i].Name,
parameters[i].ParameterType,
args.Arguments[i]));
args.Proceed();
_log.WriteLine(string.Format("{0} return value: {1}", methodName,
args.ReturnValue));
}
}