Using Postsharp to implement AOP on the. NET Platform

Source: Internet
Author: User
Tags reflector

Excerpt from:

This paper first introduces the related concepts and theories of AOP (aspect-oriented programming), then describes how to implement AOP on the. NET platform using the POSTSHARP framework, and finally makes a simple analysis of the mechanism of postsharp and the merits of AOP.

The basic definition and function of AOP (aspect-oriented programming) AOP

According to Wikipedia, "AOP (aspect-oriented programming) is a programmatic generic (programming paradigm) that separates the accessible functions of functions from business logic. The purpose of this is to separate the crosscutting concerns (cross-cutting concerns) so that the program has a higher modularity characteristics. AOP is the specific manifestation of aspect-oriented software development (aspect-oriented software development) at the level of coding implementation (aspect-oriented software development AOSD is an aspect-oriented analysis, A complete engineering system with a range of concepts such as aspect-oriented design and aspect-oriented programming-the author notes). AOP includes a programming model and a framework for implementing AOP in two parts. ”

Here are some explanations for the definitions mentioned above.

In most of the current object-oriented programming languages (such as C#,java, etc.), functions are the smallest unit that expresses program functionality, and the code level of a function often contains both core business logic and accessible functionality. The core business logic refers to the business functions that a function itself mainly implements, for example, in an online e-commerce system, the core business logic of the "PlaceOrder" function is "placing orders", while "upgrademember" function is the core business of "promoting a member's rank". However, in addition to the core business code, a function often has some auxiliary function code, such as transaction processing, cache processing, logging, exception handling and so on. These ancillary features typically exist in most or all of the business functions, namely, the so-called crosscutting concerns in Aosd, as shown in 1.

Figure 1, cross-cutting attention point schematic

The existence of crosscutting concerns has caused several problems.

    • Code writing and maintenance is difficult.

Crosscutting concerns not only cross-cutting functions, they may also be crosscutting across different classes or even different projects, leaving the same accessibility (such as transactional) scattered everywhere, and always be careful when adding new functions to add all the required crosscutting code. In addition, if you need to modify it, you need to modify all the crosscutting functions, maintenance is very difficult.

    • Introduce a lot of redundant code

Because the code for the same accessible functionality is almost identical, this will cause the same code to appear in the various functions, introducing a lot of redundant code.

    • Reduce Code Quality

Cross-cutting concerns make the core business code and auxiliary Code mix up, break the purity of business function code and the uniqueness of function responsibility, introduce a lot of complicated code and structure, make the quality of code fall.

Therefore, the core idea of AOP is to separate the crosscutting concerns when writing code, to form separate modules, to write and maintain separately, to not spread to the various business functions, so that the business functions contain only the core business code to solve the above problems. When the program is compiled or run, some means (described below) enable the independent crosscutting focus code to work automatically with the core business code to accomplish the functionality it needs.

AOP-related terminology aspects (Aspect)

A aspect refers to the specific implementation of the crosscutting concerns mentioned above in programming, which contains a specific accessibility function that is required to achieve crosscutting concerns. Specific to the code, aspect may be implemented as a class, a function, or a attribute.

Connection points (join point)

A connection point is a position or opportunity in a business function code that allows the aspect code to be inserted for execution at this location or time. Common connection points have to be entered before the function executes the business code, before the execution of the complete business code leaves the function, when an exception occurs before the exception handling code executes, and so on.

Weave in (Weaving)

Weaving refers to inserting the specified aspect code into the specified connection point, so that the crosscutting code is intertwined with the business code.

Connection models (JPM, join point model)

JPM is mainly a semantic model of aspect-oriented language (such as ASPECTJ) or aspect-oriented framework. It consists of the following three points: What connection points are available, how to specify the connection points, and how to weave them in.

How AOP is implemented

In general, it is very difficult to implement AOP in languages such as C and C + + in a purely compiled language, and you must start from the compiler's perspective completely. This article focuses on how AOP is implemented in managed languages such as C#,java. The main implementations of AOP are compile-time AOP and runtime AOP Two, which are described below.

Compile-time AOP (static weaving)

The idea of implementing AOP at compile time is to extend the compiler of the language so that when compiling the program, the compiler will weave the corresponding aspect code into the specified connection point of the business code and output the result of the integration. Figure 2 is a compile-time AOP (for example, the. NET platform).

Figure 2, compile-time AOP

2, when a static weave is used, the compiler with the AOP extension weaves the aspect code into the business function code at compile time, forming the integrated IL and then handing it over to the CLR.

Run-time AOP (dynamic weaving)

The run-time AOP3 is shown.

Figure 3, run-time AOP

As shown in 3, run-time AOP is implemented by adding extensions to the running virtual machine instead of the compiler. Aspect and business code are compiled independently, and are woven by the virtual machine when necessary at run time.

Postsharppostsharp Introduction

Postsharp is a framework for implementing AOP on the. NET platform and is an AOP framework that I use most often, the official website for Currently the latest version is 2.0, but 2.0 of license is no longer free, so it is recommended to download version 1.5, which is based on PostSharp1.5.

Postsharp uses static weaving to implement AOP, with a very rich connection point, simple to use, and relative to others. NET platform for the AOP framework, Postsharp is more lightweight, but the function is not inferior, so I prefer an AOP framework. For more information about Postsharp, please refer to its official website.

In addition to using postsharp unlike other frameworks, it is important to download the installation package, only referencing the class library, because the AOP framework needs to add extensions for the compiler or runtime, as stated above.

Implementing an AOP example using Postsharp

This section shows an example of how to implement AOP on the. NET platform using Postsharp. This example adds logging capabilities to the core business functions through AOP.

New Project

Start by creating a new C # WinForm application, as shown in 4, where the project is named "Postsharpexample".

Figure 4, new project

Writing core business functions

First, we'll write the core business. Of course there's no real business here, we're just simulating one. The core business that will be simulated is the reservation room. Build a simple UI shown in 5 first.

Figure 5, UI interface

Here we add a "corebusiness" class for the project and a "Subscribe" method in it. The code is as follows:

123456789101112 usingSystem;namespacePostSharpExample{    publicclassCoreBusiness    {        publicstaticvoidDescribe(string memberName, string roomNumber)        {            System.Windows.Forms.MessageBox.Show(String.Format("尊敬的会员{0},恭喜您预定房间{1}成功!", memberName, roomNumber), "提示");        }    }}

As you can see, the Subscribe method here is simply to output a hint box. Of course, in a real project this type of output code should not be written in the business logic, this is mainly written for the convenience of demonstration. Then, we call the Subscribe business method in Form1:

123456789101112131415161718192021 usingSystem;usingSystem.Windows.Forms;namespace PostSharpExample{    publicpartial classForm1 : Form    {        publicForm1()        {            InitializeComponent();        }        privatevoidBTN_SUBSCRIBE_Click(object sender, EventArgs e)        {            if (!String.IsNullOrEmpty(TXB_NAME.Text.Trim()) && !String.IsNullOrEmpty(TXB_ROOM.Text.Trim()))                CoreBusiness.Describe(TXB_NAME.Text.Trim(), TXB_ROOM.Text.Trim());            else                MessageBox.Show("信息不完整","提示");        }    }}

Run the program to see the corresponding effect:

Figure 6, the successful presentation of the booking room effect

Using AOP to increase logging capabilities

Join us now to add a log function to the program to record the execution of the business function. Here we assume that we need to log to a plain text file, first we complete the Logging tool class, Logginghelper.

12345678910111213141516171819 usingSystem;usingSystem.IO;namespace PostSharpExample{    classLoggingHelper    {        privateconstString _errLogFilePath = @"log.txt";        publicstaticvoidWritelog(String message)        {            StreamWriter sw = newStreamWriter(_errLogFilePath, true);            String logContent = String.Format("[{0}]{1}", DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"), message);            sw.WriteLine(logContent);            sw.Flush();            sw.Close();        }    }}

If you do not use AOP, we want to insert the logging code (WRITELOG) before and after the core business code for each method, including subscribe, and we'll see how to use Postsharp to isolate this crosscutting concern. Because you want to use Postsharp, you first add a reference to the Postsharp library file, and after you install POSTSHARP, there will be more "Postsharp.laos", "Postsharp.public", and " Postsharp.aspnet ", here we are doing the WinForm program, so just add a reference to" Postsharp.laos "and" Postsharp.public ".

Below we will write aspect, Postsharp aspect is implemented using attribute, the following is my implementation of the logging aspect code.

12345678910111213141516171819202122 usingSystem;usingPostSharp.Laos;namespace PostSharpExample{    [Serializable]    [AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited = true)]    publicsealed classLoggingAttribute : OnMethodBoundaryAspect    {        publicstring BusinessName { get; set; }        publicoverride voidOnEntry(MethodExecutionEventArgs eventArgs)        {            LoggingHelper.Writelog(BusinessName + "开始执行");        }        publicoverride voidOnExit(MethodExecutionEventArgs eventArgs)        {            LoggingHelper.Writelog(BusinessName + "成功完成");        }    }}

We agree that the naming of each aspect class must be in the form of "Xxxattribute". where "XXX" is the name of this aspect. Postsharp provides a rich built-in "Base Aspect" for us to inherit, where we Inherit "Onmethodboundaryaspect", this Aspect provides connection point methods such as entry and exit functions. In addition, "[Serializable]" must be set on the aspect, which is related to aspect's life cycle management within POSTSHARP, so see here.

Our loggingattribute is very simple, which is to log the logs to the log file when entering (Entry) and leaving (exit) functions. Now let's apply this aspect to the business approach:

12345 [logging (businessname= "book a Room" )] public   Static   void   describe (string MemberName, String roomnumber) { (String.Format ( "Dear Member {0}, congratulations on your booking of the room {1} success! "

As you can see, the application of aspect is very simple, which is to add the corresponding attribute to the business method. Now we run the scheduled room program, the result is no different from the last time, but if we open the program directory, we will see a more "Log.txt" file, there is a record similar to the contents of Figure 7.

Figure 7, log content

As you can see, we have implemented the logging functionality through AOP. After the crosscutting concerns are separated by AOP, the code for logging is placed in the loggingattribute and needs to be modified as soon as one is modified. At the same time, the business method contains only business code, which greatly improves the readability and maintainability of the program code.

A brief analysis of the operating mechanism of POSTSHARP

As already mentioned, Postsharp is using static weaving technology, let's analyze how Postsharp is implemented.

First, when you install Postsharp, it automatically adds an AOP extension to the Visual Studio compiler. If you look closely at the Postsharpexample compilation information, you will find that there are two lines:

Figure 8, Postsharp compilation information

Obviously, after the compilation of. NET Complier, the following postsharp do a part of the work, this part of the work is the static weaving process. If we use. NET Reflector to see the PostSharpExample.exe of the Subscribe method in the code, we will find a lot more things:

Figure 9, describe code after weaving into the aspect (by. NET Reflector)

These extra code, is postsharp static weaving into the. Of course, after each compilation, the Postsharp will be re-woven, so the entire process is transparent to the programmer, and we only need to maintain pure business code and aspect code.

Advantages and disadvantages of using postsharp (i.e. the advantages and disadvantages of using AOP)

In general, the use of POSTSHARP will provide the following advantages:

    • Crosscutting concerns are separated separately to improve the clarity and maintainability of the code.
    • As long as the auxiliary function code is written in aspect, the workload and redundant code are reduced to a certain extent.

Of course, the use of postsharp is not without shortcomings, the main shortcomings of the following two aspects:

    • Increased the difficulty of debugging.
    • Compared to the code without AOP, the efficiency of the operation has been reduced.

So, for the introduction of AOP, consider the tradeoffs based on the specifics of the project.

For further study of Postsharp

This article just briefly introduces Postsharp and implements a small example, does not intend to introduce in detail all aspects of postsharp, but only to think of a role. Postsharp also has a very rich function waiting for you to learn, so if you are very interested in postsharp, want to further study, please refer to the POSTSHARP official reference document.

Related Downloads

Please click here to download the example for this article.

PostSharp1.5 installation package Please click here to download.

Related Article

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: 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.