Using PostSharp in .NET projects

PHPz
Release: 2017-03-12 15:48:55
Original
4884 people have browsed it

PostSharp is a Aspect Oriented Programming aspect-oriented (or aspect-oriented) componentframework, suitable for .NET development. This article mainly introducesPostsharp related knowledge in .NET development, as well as some common aspect processing operations such as logging, caching, transaction processing, exception handling, etc.

AOP (Aspect-Oriented Programming) is a programminggeneric (programming paradigm) that separates the auxiliary functions of functions from business logic. Its purpose It separates cross-cutting concerns so that the program has higher modularity characteristics. AOP is the specific manifestation of aspect-oriented software development (Aspect-Oriented Software Development) at the coding implementation level.

We know that decoupling is what programmers have been pursuing during the coding and development process, and AOP was also born for decoupling. The introduction of AOP technology can greatly simplify our coding, reduce the amount of copied code, and make it easier to maintain unified parts of the code, such as logging, caching, transaction processing, exception handling and other commonly used processing.

1. Introduction to AOP framework

1) Introduction to AOP technology

AOP technology uses a technology called "cross-cutting" to profile Unwrap the inside of the encapsulated object, and encapsulate the public behavior that affects multiple classes into a reusable module, and name it "Aspect", that is, aspect. The so-called "aspect", simply put, is to encapsulate the logic or responsibilities that have nothing to do with the business but are commonly called by the business modules, so as to reduce the duplication of code in the system, reduce the coupling between modules, and facilitate future reliability. 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 method is like a sharp blade. Cut open these hollow cylinders to get the message inside. The cut section is the so-called "aspect". Then it restored these cut sections with incredible skill, leaving no trace.

Using "cross-cutting" technology, AOP divides the software system into two parts: core concerns and cross-cutting concerns. The main process of business processing is the core concern, and the part that has little relationship with it is the cross-cutting concern. One characteristic of cross-cutting concerns is that they often occur in multiple places in the core concern, but are basically similar everywhere. Such as authority authentication, logging, and transaction processing. The role of Aop is to separate various concerns in the system, separating core concerns and cross-cutting concerns. As Adam Magee, senior solution architect at Avanade, said, the core idea of ​​AOP is to "separate the business logic in the application program from the common services that provide support for it."

2) AOP usage scenarios

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

Authentication Permission

Caching Caching

Context passing Content passing

Error handling Error handling

Lazy loading Lazy loading

Debugging Debugging

logging, tracing, profiling and monitoring logging tracking optimization calibration

Performance optimization Performance optimization

PersistencePersistence

Resource pooling Resource pool

Synchronization Sync

Transactions Transaction

3) PostSharp framework

PostSharp is a The framework used to implement AOP on the .NET platform is a commonly used AOP framework. The official website is http://www.php.cn/. The latest version is currently 4.X, but it is a paid AOP software.

PostSharp uses static weaving method to implement AOP. Its connection points are very rich, easy to use, and compared to other AOP frameworks on some .NET platforms, PostSharp is lighter magnitude, but the functionality is not inferior at all.

Generally speaking, using PostSharp will bring the following advantages:

  • Cross-cutting concerns are separated separately, which improves 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 also some shortcomings in using PostSharp. The main disadvantages are as follows:

  • Increases the difficulty of debugging.

  • Compared with code without AOP, the operating efficiency is reduced.

However, the flaws are not concealed. Compared with these shortcomings, using PostSharp can greatly improve development efficiency, reduce duplication of code, thereby improving the readability and maintainability of the code.

In addition, there are some open source AOP components on GitHub. For example, the top one is KingAOP (http://www.php.cn/), but because it uses Dynamic way to achieve it, as its constructed object is shown below.


dynamic helloWorld = new HelloWorld();
helloWorld.HelloWorldCall();
Copy after login

Therefore, although it is more convenient and is said to be similar to PostSharp in usage habits, it changes the way objects are created and is not suitable for class object processing in general projects. Therefore, I still prefer to use PostSharp for AOP programming development.

2. Use of PostSharp framework

1) Prepare the compilation environment of PostSharp

The current version of PostSharp is 4.x , I downloaded it from the official website and used it, but "Error connecting to the pipe server. See previous warnings for details." often occurred. Later, I simply used version 3.x, but it worked 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 column of VS, as shown below.

If you need to use the PostSharp feature in a general project, in the [PostSharp] option page of the project properties, use [Add PostSharp to this project] to add PostSharp to the project. use.

After adding, the PostSharp plug-in prompt dialog box will pop up, prompting that the corresponding PostSharp package and other content will be added, as shown below.

After completion, you can use PostSharp related classes in the project.

2) Add PostSharp's AOP aspect processing

It is generally agreed that the naming of each Aspect class must be in the form of "XXXAttribute". Among them, "XXX" is the name of this Aspect. PostSharp provides a wealth of built-in "Base Aspect" for us to inherit , among which here we inherit "OnMethodBoundaryAspect". This Aspect provides connection point methods such as entering and exiting functions. In addition, "[Serializable]" must be set on Aspect, which is related to PostSharp's internal lifecycle management of Aspect.

The code of the Aspect class of the log 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);
        }
    }
Copy after login

The class code for exception handling 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);
        }
    }
Copy after login

The Aspect class 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);
        }
    }
Copy after login

The Aspect class 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();
        }
    }
Copy after login

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


        [Exception]
        [Log]        static void Calc()
        {            throw new pideByZeroException("A Math Error Occured...");
        }

        [Log, Timing]        static void LongRunningCalc()
        {            //wait for 1000 miliseconds
            Thread.Sleep(1000);
        }
Copy after login

From the above we can see that conventional exception handling and log processing have been processed through Attributes, and only the specific ones are left in the function body. The business logic code is written, which greatly improves the readability of the code and makes it concise and clear.

Run the above code function call, we can see the specific result content in the output log.


Entering [ Void Calc() ] ...
“System.pideByZeroException”类型的第一次机会异常在 PostSharpExample.exe 中发生
Exception in :[Void Calc()] , Message:[A Math Error Occured...]
Leaving [ Void Calc() ] ...


Entering [ Void LongRunningCalc() ] ...
Leaving [ Void LongRunningCalc() ] ...
[LongRunningCalc] took 1002ms to execute
Copy after login

这样,通过声明的方式,就实现了常规日志 、异常的处理,当然实际项目上使用日志、异常处理的这些代码肯定会更加复杂一些,不过小例子已经实现了切面逻辑的分离处理了,尘归尘、土归土,一切都是那么的简洁安静了。

 

The above is the detailed content of Using PostSharp in .NET projects. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!