Postsharp-lightweight Aspect-Oriented System

Source: Internet
Author: User

Postsharp -- open-source AOP framework <postsharp-lightweight Aspect-Oriented System> about AOP...

Postsharp is an exciting project. It integrates msbuild task and msil injection technology to implement AOP programming from another perspective. After the trial, you will feel the convenience. We will compare it with the previous AOP solution based on the dynamic proxy method.

* Because msil injection is used, the execution efficiency of static code injection is higher than that of Reflection emit.
* Using msbuild task allows developers to use AOP like using the built-in attribute of the compiler.
* Attackers can intercept arbitrary methods. The dynamic proxy-based AOP often intercepts Virtual Methods in the inheritance mode.
* More control. Including interrupted execution process, modification of parameters and return values.
* You can also intercept operations such as field access and exception.
* You do not need to change the object creation code to "new proxy ()", which is more transparent.
* Wildcard characters can be used for multiple interception and matching.
* Static injection brings about quality and debugging complexity of injection code.

Let's write a simple example to see the effect.
Using system;
Using system. Collections. Generic;
Using system. text;
Using system. reflection;
Using postsharp. Laos;

[Serializable]
Public class aopmethodattrict: onmethodboundaryaspect
{
Public override void onentry (methodexecutioneventargs eventargs)
{
// Obtain the method name
Console. writeline ("onentry: {0}. {1}", eventargs. method. reflectedtype, eventargs. method );

// Display method parameters
Parameterinfo [] PS = eventargs. method. getparameters ();
Object [] Pv = eventargs. getarguments ();

For (INT I = 0; I <ps. length; I ++)
{
Console. writeline ("{0 }={ 1}", PS [I]. Name, PV [I]);
}
}

Public override void onexit (methodexecutioneventargs eventargs)
{
Console. writeline ("onexit ...");
}
}

Public class myclass
{
[Aopmethod]
Public int test (int I)
{
Console. writeline ("test: {0}", I );
Return I ++;
}
}

Myclass o = new myclass ();
O. Test (123 );

Output:
Onentry: myclass. int32 test (int32)
I = 123.
Test: 123
Onexit...

The process is very simple:
1. Create a feature class inherited from onmethodboundaryaspect to intercept methods.
2. Execute the interception operation for the specific override method. Method parameters provide various operation capabilities.
3. Add features to the target method.
4. Compile and execute.

Maybe you will wonder how the aopmethodattri instance is created and executed?

1. Pay attention to the output content of the vs2005 output window during compilation. You will see the following content. In fact, postsharp provides a msbuild task, which will be called every time we compile to execute some injection operations.
Postsharp 1.0 [1.0.4.162]-copyright (c) gael fraiteur and community, 2006.

2. Use the decompilation tool to check the injected method content. After reading the code, you can even understand how it intercepts it.
Static myclass ()
{
If (!~ Postsharp ~ Laos ~ Implementation. initialized)
{
Throw new laosnotinitializedexception ();
}
~ Postsharp ~ Laos ~ Implementation .~ Targetmethod ~ 1 = methodof (myclass. test );
~ Postsharp ~ Laos ~ Implementation .~ Aspect ~ 1. runtimeinitialize (~ Postsharp ~ Laos ~ Implementation .~ Targetmethod ~ 1 );
}

Public int test (int I)
{
Int returnvalue;
Methodexecutioneventargs eventargs;
Try
{
Object [] arguments = new object [] {I };
Eventargs = new methodexecutioneventargs (methodof (myclass. Test, myclass), this, arguments );
~ Postsharp ~ Laos ~ Implementation .~ Aspect ~ 1. onentry (eventargs );
If (eventargs. flowbehavior = flowbehavior. Return)
{
Return (INT) eventargs. returnvalue;
}
Console. writeline ("test: {0}", I );
Int num = I ++;
Returnvalue = num;
Eventargs. returnvalue = returnvalue;
~ Postsharp ~ Laos ~ Implementation .~ Aspect ~ 1. onsuccess (eventargs );
Returnvalue = (INT) eventargs. returnvalue;
}
Catch (exception)
{
Eventargs. Exception = exception;
~ Postsharp ~ Laos ~ Implementation .~ Aspect ~ 1. onexception (eventargs );
Switch (eventargs. flowbehavior)
{
Case flowbehavior. Continue:
Return returnvalue;

Case flowbehavior. Return:
Return (INT) eventargs. returnvalue;
}
Throw;
}
Finally
{
Eventargs. returnvalue = returnvalue;
~ Postsharp ~ Laos ~ Implementation .~ Aspect ~ 1. onexit (eventargs );
Returnvalue = (INT) eventargs. returnvalue;
}
Return returnvalue;
}

We can use wildcards to intercept more content to simplify our encoding.
[Aopmethod (attributetargetmembers = "T *")]
Public class myclass
{
Public int T1 (int I)
{
Console. writeline ("T1: {0}", I );
Return I ++;
}

Public void T2 (string S)
{
Console. writeline ("T2: {0}", S );
}
}

Let's continue to write some other examples, such as blocking attribute access and exceptions.

Field aspect
[Serializable]
Public class aoppropertyattribute: onfieldaccessaspect
{
Public override void ongetvalue (fieldaccesseventargs eventargs)
{
Console. writeline ("exposedfieldvalue: {0}; storedfieldvalue: {1 }",
Eventargs. exposedfieldvalue, eventargs. storedfieldvalue );
}

Public override void onsetvalue (fieldaccesseventargs eventargs)
{
Console. writeline ("exposedfieldvalue: {0}; storedfieldvalue: {1 }",
Eventargs. exposedfieldvalue, eventargs. storedfieldvalue );
}
}

Public class myclass
{
[Aopproperty]
Private int X;

Public int x
{
Get {return X ;}
Set {x = value ;}
}
}

Exception aspect
[Serializable]
Public class aopexceptionattribute: onexceptionaspect
{
Public override void onexception (methodexecutioneventargs eventargs)
{
Console. writeline (eventargs. Exception. Message );
Eventargs. flowbehavior = flowbehavior. return;
}
}

Public class myclass
{
[Aopexception]
Public void test (int I)
{
Throw new exception ("error ...");
}
}

For more information, visit the postsharp website or view its help file.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.