Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does OnMethodBoundaryAspect works?

I've founded the OnMethodBoundaryAspect attribute in the PostSharp library. It can intercept entry and exit from method like this:

[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 entry and exit from method (without PostSharp using ofcourse)?

like image 859
Nelson Tatius Avatar asked Dec 27 '22 03:12

Nelson Tatius


1 Answers

First of all, I'd recommend reading following documentation for internal workings (the "how does it work" sections and others). Basically, the attributes are translated into relevant code at the build time (actually, mostly after the build but still while building). There's a notion of MSBuild task that specifies the code to be run during the build process. The code executes after the compilation is done and looks for specific attributes (like InterceptAttribute) and may perform changes to the compiled code. Runtime edits to the code may be executed while using Mono.Cecil library (it allows to inject/remove IL code). Once again, to clarify:

  1. The code is built with attributes assigned.
  2. During the build, specific code is called per BuildTasks written
  3. BuildTasks use reflection to find pieces of code that contain necessary attributes
  4. BuildTasks use Mono.Cecil to inject code dynamically to those pieces found
  5. Build is complete. Your compiled dll now contains not only the code written, but also the attributes changed into some code. I'd suggest looking at the assembly with ILSpy or similar decompilers to see the difference between your initial code and generated one.

I'd recommend looking at KindOfMagic codes to see how automatic INotifyPropertyChanged's RaisePropertyChanged is implemented as attribute. It provides valuable insights into creating custom aspects, though it may prove hard and tedious process.

like image 80
Dmitry Reznik Avatar answered Jan 17 '23 11:01

Dmitry Reznik