How does OnMethodBoundaryAspect work?

I based the OnMethodBoundaryAspect attribute in the PostSharp library . It can intercept the input and output of the method as follows:

[Serializable] [MulticastAttributeUsage(MulticastTargets.Method, Inheritance = MulticastInheritance.Multicast)] public class InterceptAttribute : OnMethodBoundaryAspect { public override void OnEntry(MethodExecutionArgs args) { } public override void OnExit(MethodExecutionArgs args) { } } public class A { [Intercept] public void foo() { } } 

And my question is: "How does it work?" What should I do to write my own attribute that will be able to intercept the input and output of the method (without using PostSharp, using the course)?

+4
source share
1 answer

First of all, I would recommend reading the following documentation for internal work (sections on how it works, etc.). In principle, attributes are translated into the appropriate code during assembly (in fact, mainly after assembly, but during creation). There is the concept of an MSBuild task , which indicates the code that must be run during the build process. The code is executed after compilation and looks for specific attributes (for example, InterceptAttribute) and can make changes to the compiled code. Editing the runtime of the code can be performed using the Mono.Cecil library (this allows you to enter / delete IL-code). Once again, to clarify:

  • The code is built with assigned attributes.
  • During build, specific code is invoked in each BuildTasks entry.
  • BuildTasks uses reflection to search for code snippets containing necessary attributes
  • BuildTasks uses Mono.Cecil to dynamically enter code into found fragments
  • Assembly completed. The compiled dll now contains not only written code, but also attributes changed to some code. I would suggest looking at the build with ILSpy or similar decompilers to see the difference between your source code and the generated one.

I would recommend looking at KindOfMagic codes to find out how the automatic INotifyPropertyChanged RaisePropertyChanged function is implemented as an attribute. This provides valuable information on creating custom aspects, although it can be a difficult and tedious process.

+9
source

Source: https://habr.com/ru/post/1403212/


All Articles