Postsharp is a aspect oriented Programming component framework for facets (or aspect-oriented). NET development, this article mainly introduces the knowledge of Postsharp in. NET development, as well as some common slice processing operations such as log, cache, transaction processing, exception handling.
AOP (aspect-oriented programming) is a programmatic generic (programming paradigm) that separates the accessible functions of functions from business logic, and is intended to be a cross-cutting concern (cross-cutting Concerns), which allows the program to have higher modularity characteristics. AOP is the specific performance of aspect-oriented software development (aspect-oriented software development) at the level of coding implementation.
We know that decoupling is something that has been pursued in the programmer's coding development process, and that AOP was created to understand the decoupling. The introduction of AOP technology can greatly simplify our coding, reduce the amount of code copied, and also facilitate the uniform maintenance of some common code, such as log, cache, transaction processing, exception handling and other commonly used processing.
1. Introduction to the AOP framework
1) Introduction to AOP Technology
AOP technology uses a technique called "crosscutting" that splits the encapsulated object interior and encapsulates public behavior that affects multiple classes into a reusable module, called "Aspect", which is the facet. The so-called "aspect", in a nutshell, is to encapsulate the logic or responsibility that is not related to the business, but for the common invocation of the business module, to reduce the duplication of code in the system, to reduce the coupling between modules, and to facilitate future operability and maintainability. AOP represents a horizontal relationship, if the "object" is a hollow cylinder, which encapsulates the properties and behavior of the object, then the aspect-oriented programming approach is like a razor that cuts through the hollow cylinders to get inside the message. The cut-off aspect is the so-called "facet". Then it hands the cut-off slices with a clever capture of the heavens, leaving no traces.
Using "crosscutting" techniques, AOP divides software systems into two parts: core concerns and crosscutting concerns. The main process of business process is the core concern, and the part that has little relation is the crosscutting concern. One feature of crosscutting concerns is that they often occur in many of the core concerns and are essentially similar everywhere. such as permission authentication, logging, transaction processing. The role of AOP is to separate the various concerns in the system, separating the core concerns from the crosscutting concerns. As Avanade's senior program architect Adam Magee says, the core idea of AOP is "separating the business logic in the application from the generic services that support it." ”
2) AOP Usage Scenarios
AOP is used to encapsulate crosscutting concerns, which can be used in the following scenarios:
Authentication Permissions
Caching Cache
Context Passing content delivery
Error handling Errors Handling
Lazy Loading lazily loaded
Debugging commissioning
Logging, tracing, profiling and monitoring record tracking optimization calibration
Performance Optimization Performance optimization
Persistence persistence
Resource Pooling resource Pool
Synchronization synchronization
Transactions transactions
3) Postsharp Frame
Postsharp is a framework for implementing AOP on the. NET platform and is a more commonly used AOP framework, and the official website is http://www.sharpcrafters.com. Currently the latest version is 4. X, but is a fee for AOP software.
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.
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, there are some drawbacks to using POSTSHARP, and the main drawbacks are as follows:
- Increased the difficulty of debugging.
- Compared to the code without AOP, the efficiency of the operation has been reduced.
However, with respect to these shortcomings, the use of postsharp can greatly improve the development efficiency and reduce duplication of code, thus improving the readability and maintainability of the code. His flaws
There are also some open source AOP components on GitHub, such as KINGAOP (Https://github.com/AntyaDev/KingAOP), but because it is implemented in a dynamic way, such as its construction object is as follows.
Dynamic New HelloWorld (); Helloworld.helloworldcall ();
Therefore, although it is more convenient, and known as the use of postsharp similar, but changed the way objects are created, the general project of the Class object processing is not very suitable. So I prefer to use POSTSHARP to develop AOP programming.
2, the use of POSTSHARP framework
1) Prepare the POSTSHARP compilation environment
Postsharp current version is 4.x, I downloaded it on the official website for use, but often occurs "Error connecting to the pipe server." See previous warnings for details. ", and then simply use the 3.x version, but can use normally, very good, hehe.
Postsharp is a plug-in that can be installed on VS and Adds a Postsharp menu item to the VS menu after installation, as shown below.
General items if you need to use the Postsharp attribute, in the Postsharp Options page of the project properties, use "Add Postsharp to this project" to add the Postsharp to the projects.
Once added, the Postsharp plugin prompt dialog box pops up, prompting you to add the appropriate Postsharp package, as shown below.
Once you're done, you can use Postsharp's related classes in your project.
2) Increase Postsharp AOP processing
It is generally agreed that the name 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 aspect, which is related to aspect life cycle management within POSTSHARP.
The code for the Aspect class of the log is shown below.
[Serializable] Public classLogattribute:onmethodboundaryaspect { Public Override voidonentry (Methodexecutionargs args) {Console.WriteLine (Environment.NewLine); Console.WriteLine ("Entering [{0}] ...", args. Method); Base. OnEntry (args); } Public Override voidOnExit (Methodexecutionargs args) {Console.WriteLine ("leaving [{0}] ...", args. Method); Base. OnExit (args); } }
The class code for exception handling is shown below.
[Serializable] publicclass exceptionattribute:onexceptionaspect { Public Override void onexception (Methodexecutionargs args) { Console.WriteLine (String.Format ("Exception in: [{0}], message:[{1}]" , args. Method, args. Exception.Message)); = flowbehavior.continue; Base . Onexception (args); } }
The aspect class code for timing processing is shown below.
[Serializable] [Multicastattributeusage (Multicasttargets.method)] Public classTimingAttribute:PostSharp.Aspects.OnMethodBoundaryAspect {[nonserialized] Stopwatch _stopwatch; Public Override voidonentry (PostSharp.Aspects.MethodExecutionArgs args) {_stopwatch=stopwatch.startnew (); Base. OnEntry (args); } Public Override voidOnExit (PostSharp.Aspects.MethodExecutionArgs args) {Console.WriteLine (string. Format ("[{0}] took {1}ms to execute", NewStackTrace (). GetFrame (1). GetMethod (). Name, _stopwatch.elapsedmilliseconds)); Base. OnExit (args); } }
The Aspect class code for the transaction is shown below.
[Serializable] [Aspecttypedependency (Aspectdependencyaction.order, Aspectdependencyposition.after,typeof(Logattribute))] Public classRunintransactionattribute:onmethodboundaryaspect {[nonserialized] TransactionScope Transactionsco Pe Public Override voidonentry (Methodexecutionargs args) { This. TransactionScope =NewTransactionScope (transactionscopeoption.requiresnew); } Public Override voidonsuccess (Methodexecutionargs args) { This. Transactionscope.complete (); } Public Override voidonexception (Methodexecutionargs args) {args. Flowbehavior=flowbehavior.continue; Transaction.Current.Rollback (); Console.WriteLine ("Transaction was unsuccessful!"); } Public Override voidOnExit (Methodexecutionargs args) { This. Transactionscope.dispose (); } }
Here are the facets of several aspect classes of code, as shown below.
[Exception] [Log] static void Calc () { throw new dividebyzeroexception ( " a Math Error occured ... " ); } [Log, Timing] static void Longrunningcalc () { // wait for miliseconds thread.sleep (1000 ); }
From the above we can see that the normal exception handling, log processing has been processed by attribute, in the function body is only the specific business logic code, which greatly improve the readability of the code, concise and clear.
Run the call of the above code function, we can see the concrete result content in the output log.
inch : [Void Calc ()], message:[a Math Error occured ...] Leaving [Void Calc ()] ... Entering [Void Longrunningcalc ()] ... Leaving [Void Longrunningcalc ()] ... [Longrunningcalc] took 1002ms to execute
Thus, through the declaration of the way, the implementation of the regular log, exception processing, of course, the actual project on the use of logs, exception handling of these code will certainly be more complex, but the small example has realized the separation of the plane logic processing, dust to dust, soil to earth, everything is so concise and quiet.
Using Postsharp in. NET projects to implement AOP-oriented tangent-to-surface programming