First of all, it is necessary to first introduce what is called AOP (aspect-oriented programming, aspect-oriented programming). Is Baidu's entry explanation
It may be more straightforward to interpret the diagram as:
PS: Pictures from http://www.cnblogs.com/leoo2sk/archive/2010/11/30/aop-postsharp.html
To put it simply, AOP is a cross-cutting concern, such as exception handling, logging, and so on, that is independent of the system's business logic.
--------------------------------------------------------------------------------------------------------------- -----------
Before in the project, often encountered the problem is: How to add a unified method of exception handling all methods, especially CS mode (BS mode is relatively simple, you can catch exceptions in the global file, and record). In addition to the previous interview, also asked a similar question, I thought for a long time, or can not think of any good way. Later today, when I look at MVC4 Web programming, it is mentioned that the exception log can be logged uniformly by attributes. So, I was ecstatic, hurriedly Baidu related technical articles, found a very useful AOP plug-in, that is, the protagonist of this article: Postsharp
1. Download Postsharp (https://www.postsharp.net/). Now the version has been updated to 4.1. 1.5 is free, more than 2.0 of the version is charged. I have a 3.0 version and a keygen. Need to add me Q (371323761)
2. Install the Postsharp. The process is simple and can be followed by its process. Follow, open keygen, generate license can.
3. Open VS, right-click Project, select Add Postsharp to project, for example, then you can use Postsharp to write some AOP applications.
--------------------------------------------------------------------------------------------------------------- -
For example, we want to make an exception log for each method of each class
1. Defining Logging Classes
namespace customattribute{ publicinterface ILog { void log ( String msg);} }
[Serializable] Public classLogger:ilog { Public voidLogstringmsg) { stringPath = Environment.currentdirectory +"\\"+string. Format ("systemlog/{0}/{1}/{2}","Error", DateTime.Now.Year, DateTime.Now.Month); if(!directory.exists (path)) {directory.createdirectory (path); } stringLogPath = path +"/"+ DateTime.Today.ToString ("YYYY-MM-DD") +". txt"; if(!file.exists (LogPath)) { varFile =file.create (LogPath); File. Close (); } StreamWriter SW=NewStreamWriter (LogPath,true); Sw. WriteLine (msg); Sw. Flush (); Sw. Close (); } }
2. Defining the characteristics of an exception log record
[Serializable] [AttributeUsage (AttributeTargets.Method, AllowMultiple=true, inherited =true)] Public classExceptionlogattribute:onmethodboundaryaspect {PrivateILog logger;//decoupling via dependency injection PublicExceptionlogattribute (ILog log) {logger=log; } Public Override voidonexception (Methodexecutionargs args) {Base. Onexception (args); Logger.log (string. Format ("{0}:{1}", DateTime.Now.ToString ("YYYY-MM-DD HH:mm:ss"), args. Exception.Message)); } }
[Serializable] true true )]//AttributeTargets.Method shows that this feature is applied to the method
Public Sealed class public Base (new Logger ()) {}}
3. Apply the feature to the method
class program { staticvoid Main (string[] args) { Console.WriteLine (Divide ( 10)); Console.ReadLine (); } [Myexceptionlog] Private Static int Divide (intint b) { return A/ b; } }
4. Results
Postsharp still have a lot of use, and then dig slowly.
Very like Postsharp official online sentence:
Start Writing Cleaner Code
Today!
Previously written code always focused on how to implement the function, and then slowly learn to refactor the code in design mode, now understand the AOP (POSTSHARP), you can from another angle, in a more elegant way to write code.
------------------------
Question 1: What if you want to define the characteristics of a uniform exception logging for all methods of a class?
If you define an attribute targets as all or class, you can catch exceptions for all methods of that class
2: What happens if you want to define the characteristics of exception logging for each method in an assembly (DLL)?
Define the targets of the attribute as all or assembly, and then in the AssemblyInfo.cs file, add the attributes of the assembly
Postsharp First Experience