Using PostSharp in .NET projects
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();
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); } }
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); } }
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); } }
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(); } }
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); }
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
这样,通过声明的方式,就实现了常规日志 、异常的处理,当然实际项目上使用日志、异常处理的这些代码肯定会更加复杂一些,不过小例子已经实现了切面逻辑的分离处理了,尘归尘、土归土,一切都是那么的简洁安静了。
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Whether you are a beginner or an experienced professional, mastering C# will pave the way for your career.

The development of artificial intelligence (AI) technologies is in full swing today, and they have shown great potential and influence in various fields. Today Dayao will share with you 4 .NET open source AI model LLM related project frameworks, hoping to provide you with some reference. https://github.com/YSGStudyHards/DotNetGuide/blob/main/docs/DotNet/DotNetProjectPicks.mdSemanticKernelSemanticKernel is an open source software development kit (SDK) designed to integrate large language models (LLM) such as OpenAI, Azure

If you are a .NET developer, you must be aware of the importance of optimizing functionality and performance in delivering high-quality software. By making expert use of the provided resources and reducing website load times, you not only create a pleasant experience for your users but also reduce infrastructure costs.

In terms of high-concurrency request processing, .NETASP.NETCoreWebAPI performs better than JavaSpringMVC. The reasons include: AOT early compilation, which reduces startup time; more refined memory management, where developers are responsible for allocating and releasing object memory.

C#.NET interview questions and answers include basic knowledge, core concepts, and advanced usage. 1) Basic knowledge: C# is an object-oriented language developed by Microsoft and is mainly used in the .NET framework. 2) Core concepts: Delegation and events allow dynamic binding methods, and LINQ provides powerful query functions. 3) Advanced usage: Asynchronous programming improves responsiveness, and expression trees are used for dynamic code construction.

Interview with C# senior developer requires mastering core knowledge such as asynchronous programming, LINQ, and internal working principles of .NET frameworks. 1. Asynchronous programming simplifies operations through async and await to improve application responsiveness. 2.LINQ operates data in SQL style and pay attention to performance. 3. The CLR of the NET framework manages memory, and garbage collection needs to be used with caution.

C# is a modern, object-oriented programming language developed by Microsoft and as part of the .NET framework. 1.C# supports object-oriented programming (OOP), including encapsulation, inheritance and polymorphism. 2. Asynchronous programming in C# is implemented through async and await keywords to improve application responsiveness. 3. Use LINQ to process data collections concisely. 4. Common errors include null reference exceptions and index out-of-range exceptions. Debugging skills include using a debugger and exception handling. 5. Performance optimization includes using StringBuilder and avoiding unnecessary packing and unboxing.

C#.NETisversatileforbothwebanddesktopdevelopment.1)Forweb,useASP.NETfordynamicapplications.2)Fordesktop,employWindowsFormsorWPFforrichinterfaces.3)UseXamarinforcross-platformdevelopment,enablingcodesharingacrossWindows,macOS,Linux,andmobiledevices.
