AOP – Aspect Oriented Programming allows you to decorate all methods before and after execute them using a proxy pattern.
In this article, we will build a simple application using Unity Microsoft Framework to apply AOP.
First download Unity framework: http://unity.codeplex.com/releases
Create a console application solution and
Reference two Unity assemblies:
-Microsoft.Practices.Unity which allows Dependency injection (see an article below)
-Microsoft.Practices.Unity.Interception allowing Aspect Oriented Programming
Add to the solution two folders:
-AOP : Folder for the class used to decorate our Business class
-BIZ: Folder for a simple Business service
Create a PerformanceHandler class which implements ICallHandler interface.
Use the unity interception namespace:
Below, we set a stopwatcher to mesure the execution time of the method called
And we print in console the interception before and after call really the method
The ICallHandler interface have an invoke method where you decorate your method (proxy pattern). You can make technical log, get the methode name decorated, set your security strategy…
Add a new class , PerformanceAttribute which implement HandlerAttribute and override CreateHandler method to return an instance of PerformanceHandler.
This class create an attribute you have to set before a method you want to decorate
in our folder BIZ, create a simple Business service and its interface:
and its interface IBizService. Note that we decorate execute method with Performance Attribute (our PerformanceAttribute class):
Now add the following code in the main program:
Execute, and you will stop at differents place where we set a Console.ReadLine()
Before the execute method of our service is runned
Press enter key : the method is executed and new print appears after
the execution is completed and we return on our main program