Here's the last post in my series of AOP terminology posts.
This week's term is "weaving".
Weaving is a general term to describe how an AOP tool combines an aspect with the rest of your code.
There are two main methods of weaving:
- Post-compiliation - modifying the code after the program already been compiled
- Runtime - Modifying/replacing the code while the program is running
Castle DynamicProxy uses runtime weaving. You can think of it as just like using the decorator pattern, except instead of coding each decorator by hand, Castle DynamicProxy will create those classes for you at runtime, by combining the IInterceptor implementation (that you've created) with the object that you want to intercept.
PostSharp is a post-compiler tool. It will take the aspect class that you've defined and actually modify your compiled program to weave it in to the methods/properties/etc you want it to intercept. I think a good way to visualize this is by using a decompiler to see what the code looks like before and after PostSharp has modified it.
Here's a very basic console app with a single aspect applied to a single method.
Here's what it looks like after compiling with PostSharp turned off and then decompiling (I used ILSpy as the decompiling tool this time):
Here's what it looks like after compiling with PostSharp turned on and then decompiling:
Don't panic, it's not as complicated as it looks: don't let the weird naming throw you off. Notice line 23: that's the only line that I wrote inside of the DoStuff method. The rest all comes from the aspect. The try/catch/finally structure was all put in to place by PostSharp. The first line of the method now calls the OnEntry method that I defined in the aspect. The OnSuccess method is the last thing called inside the Try. The OnException is called inside of the Catch. And OnExit is called inside of the Finally. (Note: they all get null arguments because I don't actually do anything of value inside the aspect, otherwise you'd also see some code to create the argument objects to pass in).
You can see that even though your source code is separated out into two classes, PostSharp does the work of weaving the cross-cutting concerns into the other method.