This article is a mirror article of machine translation, please click here to jump to the original article.

View: 21364|Reply: 1

[Source] .net/C# uses Attributes to implement simple AOP

[Copy link]
Posted on 4/18/2017 2:54:11 PM | | |

Let's start with a simple piece of code:



So let's say this is a web program, we want to check the session first, then check the permissions, start a transaction, write a log, then execute the operation itself, and finally write a log. Obviously, we can't write all the method calls to the above operations in DoSomething(), so the code will become a big piece of shit, so what should we do?

There are many ways to implement it, such as using frameworks such as spring, but in actual projects, it is not possible to introduce a framework casually, and many times we need to write some mechanisms by ourselves.

Here I think of the Filter in MVC, as long as you put an attribute tag on the Controller or Action, you can do some other things before and after the method is executed. So let's simply simulate a filter implementation.

First of all, the original method is transformed into an elegant way of feature labels:




With feature tags, there must be classes corresponding to feature tags, as well as AOP implementations, which can be independently contained in a file or assembly.

First, the label attached to the method, implemented as empty:

//贴在方法上的标签
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public sealed class MyInterceptorMethodAttribute : Attribute { }
After that, define the label to be attached to the class:




Here is a MyAopHandler class defined, implemented as follows:




Note that the specific operation part of the code above is equivalent to a "proxy class", which essentially changes the context of the method execution. Object-oriented program structures such as delegates can be used to expose the specific implementation to the outside world for secondary development.




Previous:ES5, ES6, ES2016, ES. Next: What's going on with the version of Javascrip{filter}t?
Next:PowerShell Getting Started Tutorial - v0.3 version
Disclaimer:
All software, programming materials or articles published by Code Farmer Network are only for learning and research purposes; The above content shall not be used for commercial or illegal purposes, otherwise, users shall bear all consequences. The information on this site comes from the Internet, and copyright disputes have nothing to do with this site. You must completely delete the above content from your computer within 24 hours of downloading. If you like the program, please support genuine software, purchase registration, and get better genuine services. If there is any infringement, please contact us by email.

Mail To:help@itsvse.com