Aspect Orientated Programming with PostSharp.
I have recently discovered Aspect Orientated Programming or AOP, I know it is a bit late but rather late than never. Wikipedia has a great article on it: Aspect-Orientated Programming. The real benefit of AOP is that you remove all code that is not core to your functionality within a method such as Logging and Exception Handling.
It allows you to have crosscutting code in one location and if you make any changes to the signature of the code, you don’t have to go wading through all your code changing method calls etc.
I have been using a great extension called PostSharp, made by sharpCrafters. it comes with a free Trial and Community version, but also has paid for licences as well.
The following example creates an exception attribute that inherits the OnExceptionAspect which is defined in the namespace PostSharp.Aspects. The attribute is called an Aspect, the method OnException is called an advice and it will be called whenever an exception is thrown in the decorated method, in this case CauseException(); So here, I am giving the method CauseException advice on what to do with exceptions.
So go on, download PostSharp and give AOP a try!
using System;
using System.Diagnostics;
using PostSharp.Aspects;
namespace AOPConsole
{
[Serializable]
public sealed class ExceptionAttribute : OnExceptionAspect
{
public ExceptionAttribute()
{
}
public override void OnException(MethodExecutionArgs args)
{
Trace.WriteLine(String.Format("Exception - {0}.{1}: {2} - {3}",args.Method.DeclaringType.Name, args.Method.Name, args.Exception.Message, args.Exception.StackTrace));
}
}
class Program
{
static void Main(string[] args)
{
System.Diagnostics.Trace.Listeners.Add(new System.Diagnostics.TextWriterTraceListener(Console.Out));
CauseException();
Console.ReadKey(true);
}
[ExceptionAttribute()]
private static void CauseException()
{
object nullObject = null;
int intObject = (int)nullObject;
}
}
}
