Use PostSharp in the. NET project to implement Aspect-Oriented AOP programming, postsharpaop

Source: Internet
Author: User

Use PostSharp in the. NET project to implement Aspect-Oriented AOP programming, postsharpaop

PostSharp is an Aspect Oriented Programming cross-section (or Aspect-Oriented) component framework, applicable. NET development, this article mainly introduces Postsharp in. NET development knowledge, as well as some common section processing operations such as logs, caches, transaction processing, and Exception Processing.

AOP (Aspect-Oriented Programming) is a programming generic model that separates the auxiliary functions of a function from the business logic ), the purpose is to separate the cross-cutting concerns to make the program more modular. AOP is a specific manifestation of Aspect-Oriented Software Development at the coding implementation level.

We know that decoupling is a constant pursuit of coding development by programmers, and AOP is also born for decoupling. The introduction of AOP technology can greatly simplify coding, reduce the amount of copied code, and facilitate the unified maintenance of some of the Code, such as log, cache, transaction processing, Exception Processing, and other common processing.

1. Introduction to the AOP framework

1) Introduction to AOP technology

AOP uses a technology called "cross-cutting" to segment the encapsulated objects and encapsulate the public behaviors that affect multiple classes into a reusable module, and name it "Aspect", that is, Aspect. The so-called "aspect" is simply to encapsulate the logic or responsibilities that are irrelevant to the business but are called by the business module to reduce repeated system code, reduce the coupling between modules and facilitate future operability and maintainability. AOP represents a horizontal relationship. If "object" is a hollow cylinder that encapsulates the attributes and behaviors of objects, then the method for Aspect-Oriented Programming is, it is like a sharp blade that splits these hollow cylinders to obtain internal messages. The cut section is the so-called "aspect. Then it restored these cut sections with the skill of winning the power of heaven without leaving any trace.

Using the "cross-cutting" technology, AOP divides the software system into two parts: the core focus and the cross-cutting focus. The main process of business processing is the core focus, and the part that has little to do with it is the cross-cutting focus. One feature of cross-cutting concerns is that they often occur in multiple places of core concerns, and are similar everywhere. For example, permission authentication, logs, and transaction processing. The function of Aop is to separate the various concerns in the system from the core concerns and the cross-cutting concerns. As Adam Magee, Avanade's senior Solution Architect, said, the core idea of AOP is to "separate the business logic in applications from the general services it supports ."

 

2) Use Cases of AOP

AOP is used to encapsulate cross-cutting concerns. It can be used in the following scenarios:

Authentication permission

Caching Cache

Context passing content transmission

Error handling

Lazy loading

Debugging

Logging, tracing, profiling and monitoring record tracking optimization Calibration

Performance optimization

Persistence

Resource pooling Resource pool

Synchronization

Transactions transaction

 

3) PostSharp framework

PostSharp is a framework used to implement AOP on the. NET platform, is a commonly used AOP framework, the official website for http://www.sharpcrafters.com. Currently, the latest version is 4.X, but it is a paid AOP software.

PostSharp uses the static weaving method to implement AOP. It has a wide range of connection points and is easy to use. for the AOP framework on the NET platform, PostSharp is relatively lightweight, but its functions are not inferior at all.

In general, using PostSharp will bring about the following advantages:

  • The cross-cutting concerns are separated separately, improving the clarity and maintainability of the Code.
  • As long as you write helper code in Aspect, the workload and redundant code are reduced to a certain extent.

Of course, the use of PostSharp also has some shortcomings, the main disadvantages are as follows:

  • This increases the difficulty of debugging.
  • Compared with Codes Without AOP, the running efficiency is reduced.

However, it is easy to hide your skills. Compared with these shortcomings, using PostSharp can greatly improve development efficiency and reduce repeated code, thus improving code readability and maintainability.

In addition, there are some open source AOP components on GitHub, such as KingAOP (https://github.com/AntyaDev/KingAOP), but because it adopts the Dynamic method to achieve, such as its construction object is as follows.

dynamic helloWorld = new HelloWorld();helloWorld.HelloWorldCall();

Therefore, although it is convenient and similar to PostSharp, it changes the object creation method and is not suitable for Class Object processing in general projects. Therefore, I am more inclined to use PostSharp for AOP programming and development.

 

2. Use of the PostSharp framework

1) Prepare the PostSharp compiling environment

The current PostSharp version is 4.x. I have downloaded it from the official website, but "Error connecting to the pipe server often occurs. see previous warnings for details. ", then I simply used 3. x version, but can be used normally, very good, haha.

PostSharp is a plug-in that can be installed on VS. After installation, a PostSharp menu item is added to the menu bar of VS, as shown below.

If PostSharp is required for a project, Add PostSharp to this project to Add PostSharp to the project on the "PostSharp" option page of the project attribute.

The PostSharp plug-in prompt dialog box appears, prompting you to add the corresponding PostSharp package, as shown below.

After that, you can use the PostSharp class in the project.

 

2) added the AOP aspect processing of PostSharp.

It is generally agreed that each Aspect class must be named in the form of "XXXAttribute. "XXX" is the name of this Aspect. PostSharp provides a wide range of built-in "Base Aspect" for us to inherit. Here we inherit "OnMethodBoundaryAspect", which provides connection points such as entry and exit functions. In addition, "[Serializable]" must be set on Aspect, which is related to Aspect lifecycle management in PostSharp.

The log's Aspect class code is as follows.

    [Serializable]    public class LogAttribute : OnMethodBoundaryAspect    {        public override void OnEntry(MethodExecutionArgs args)        {            Console.WriteLine(Environment.NewLine);            Console.WriteLine("Entering [ {0} ] ...", args.Method);            base.OnEntry(args);        }        public override void OnExit(MethodExecutionArgs args)        {            Console.WriteLine("Leaving [ {0} ] ...", args.Method);            base.OnExit(args);        }    }

The exception handling class code is as follows.

    [Serializable]    public class ExceptionAttribute : OnExceptionAspect    {        public override void OnException(MethodExecutionArgs args)        {            Console.WriteLine(String.Format("Exception in :[{0}] , Message:[{1}]", args.Method, args.Exception.Message));            args.FlowBehavior = FlowBehavior.Continue;            base.OnException(args);        }    }

The Aspect code for timing processing is as follows.

    [Serializable]    [MulticastAttributeUsage(MulticastTargets.Method)]    public class TimingAttribute : PostSharp.Aspects.OnMethodBoundaryAspect    {        [NonSerialized]        Stopwatch _StopWatch;        public override void OnEntry(PostSharp.Aspects.MethodExecutionArgs args)        {            _StopWatch = Stopwatch.StartNew();            base.OnEntry(args);        }        public override void OnExit(PostSharp.Aspects.MethodExecutionArgs args)        {            Console.WriteLine(string.Format("[{0}] took {1}ms to execute",              new StackTrace().GetFrame(1).GetMethod().Name,                _StopWatch.ElapsedMilliseconds));            base.OnExit(args);        }    }

The Aspect code for transaction processing is as follows.

    [Serializable]    [AspectTypeDependency(AspectDependencyAction.Order, AspectDependencyPosition.After, typeof(LogAttribute))]    public class RunInTransactionAttribute : OnMethodBoundaryAspect    {        [NonSerialized]        TransactionScope TransactionScope;        public override void OnEntry(MethodExecutionArgs args)        {            this.TransactionScope = new TransactionScope(TransactionScopeOption.RequiresNew);        }        public override void OnSuccess(MethodExecutionArgs args)        {            this.TransactionScope.Complete();        }        public override void OnException(MethodExecutionArgs args)        {            args.FlowBehavior = FlowBehavior.Continue;            Transaction.Current.Rollback();            Console.WriteLine("Transaction Was Unsuccessful!");        }        public override void OnExit(MethodExecutionArgs args)        {            this.TransactionScope.Dispose();        }    }

The following is the section processing code of several Aspect classes, as shown below.

        [Exception]        [Log]        static void Calc()        {            throw new DivideByZeroException("A Math Error Occured...");        }        [Log, Timing]        static void LongRunningCalc()        {            //wait for 1000 miliseconds            Thread.Sleep(1000);        }

As we can see from the above, regular Exception Processing and log processing have all been processed through the Attribute method, and only the specific business logic code is left in the function body, this greatly improves the readability and simplicity of the Code.

Run the above Code function call. We can see the specific results in the output log.

Entering [Void Calc ()]... "System. divideByZeroException "type first opportunity Exception occurs in PostSharpExample.exe Exception in: [Void Calc ()], Message: [A Math Error Occured...] leaving [Void Calc ()]... entering [Void LongRunningCalc ()]... leaving [Void LongRunningCalc ()]... [LongRunningCalc] took 1002 ms to execute

In this way, regular logs and exceptions are processed through declarations. Of course, the code for using logs and Exception Handling in actual projects will be more complex, however, the small example has implemented the separation of the Plane Surface logic. Dust Collection and soil conversion are all so concise and quiet.

 

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