четверг, 19 марта 2015 г.

PostSharp in Depth Part 2. How does my code look like?

In this post i want to reveal what PostSharp does for us in case when we use aspects derived from OnMethodBoundaryAspect class.

Let's create the same simple Console application with one method Log, and mark it with an attribute based on aspect class derived from MethodInterceptionAspect class:

1:  using System;  
2:  using PostSharp.Aspects;  
3:  namespace HelloWorld  
4:  {  
5:    class Program  
6:    {  
7:      static void Main(string[] args)  
8:      {  
9:         Log("test");  
10:        Console.ReadLine();  
11:      }  
12:      [AspectBasedOnInterception]  
13:      private static void Log(string name)  
14:      {  
15:        Console.WriteLine(name);  
16:      }  
17:    }  
18:    [Serializable]  
19:    public class AspectBasedOnInterception : MethodInterceptionAspect  
20:    {  
21:      public override void OnInvoke(MethodInterceptionArgs args)  
22:      {  
23:        Console.WriteLine("Test");  
24:        args.Proceed();  
25:      }  
26:    }  
27:  }  

The main difference in generated code is that when you use aspect derived from OnMethodBoundary class, PostSharp adds to your initial method body some infrastructure code. But when you use aspect derived from MethodInterceptionAspect it completely replace your method body with infrastructure code.
In my case body of the Log method was moved into <Log>c__Binding class. Which is private class in Program class. By design it's singleton class with private constructor, accessed through public static field and one method Invoke, here it is:


The marked line is our initial Console.WriteLine(name). And our initial method Log in Program class now looks like this:


It only configure our AspectBasedOnInterception instance class and call its OnInvoke method(line 34). And it's OnInvoke method of our aspect:


So, what PostSharp did for us:
  1. Replaced our method body with own infrastructure code.
  2. Moved initial method body into private class designed as singleton.
  3. In this infrastructure code created reference at singleton class and pass it into Aspect class instance
  4. Calls our aspect
PS. I used VS 2013, .NET 4.5, PostSharp 4.0.42.




 

Комментариев нет:

Отправить комментарий