Abstract: (3) AOP programming and ASP. NET MVC

Source: Internet
Author: User

AOP (Aspect Oriented Programming) for aspect programming. It is hard to understand the aspect. Where is the aspect of the code? It is not a 3D object. The concept doesn't matter. Let's understand this term from its thoughts. The main idea of AOP is to extract the same, similar, and scattered logic for unified processing. This not only facilitates maintenance, but also makes the code more focused on itself and clearer.

For example, common permission checks, logging, and exception handling are scattered in various places of the system, such as the Code for posting an article:

Public void post (article) {If (currentuser is null) throw new authexception ("You have not logged on"); elsearticlemanager. Save (Article );}

This is what can be done by articlemanager. Save in one sentence. Now we need to add If else to handle the exception, and the code is difficult to maintain. Assume that

[Authorize]public void Post(Article article){ArticleManager.Save(article);}

Using authroizeattribute to handle permission issues, the code is much clearer and can be reused. The idea of this attribute is the idea of AOP.
Of course, attribute is only an implementation method. before calling the POST method, attribute is obtained through reflection and its code is executed,
The most commonly used AOP is in the ASP. net mvc framework. This authorizeattribute is provided by MVC. We can rewrite some of his methods to achieve the desired functions (such as permission levels ).

For another example, if we have a unified Exception Handling logic, we can directly throw the exception instead of try/catch in the logic code, this will make the code more clean.
(PS: It doesn't mean that there is no need to try/catch after unified processing, and some exceptions should be eaten. This depends on the specific business needs. In addition, catch should be noted for exceptions that cannot be captured, such as exceptions in the thread .)
For example:

Public void post (article) {If (string. isnullorempty (article. title) {Throw new argumentmissexception ("title ");}... articlemanager. save (Article);} protected override void onexception (exceptioncontext filtercontext ){//.. exception Handling Code}

As long as the onexception method provided by MVC is rewritten, all exceptions can be handled, displayed to a user-friendly error interface, or exception logs can be easily sent, instead of writing the processing code everywhere.
For further consideration, if the exception information is processed in a unified manner, the design and application of the exception class should be taken into consideration.

In addition, let's look at the above Code. If there are multiple places that need post (Article), but they are completely inconsistent, but the field check is consistent, the code for field check will be repeated. In this case, either use a separate method to verify the effectiveness of the article, call it in various places, or use the modelbinder provided by MVC, this is also the AOP method implemented through the attribute of the parameter. MVC is too thoughtful and has to be liked.

Public void post ([articlebinder] Article) {// you do not need to write the verification code about article again here. save (Article);} public class articlebinderattribute: custommodelbinderattribute {class articlebinder: imodelbinder {public object bindmodel (controllercontext, modelbindingcontext bindingcontext) {// although you have customized binder, however, it is not as comfortable as the action parameter to obtain the parameter value here. VaR Title = controllercontext. routedata. values ["title"]. tostring (); If (string. isnullorempty (title) {Throw new argumentnullexception ("title");} return new article {Title = title };}public override system. web. MVC. imodelbinder getbinder () {return New articlebinder ();}}

  

The use of the AOP provided by the framework is very simple and comfortable, but we cannot only use application-level programmers when using other frameworks. We need to understand its ideas, understand its nature, and understand its implementation.
Fortunately, MVC is open-source. We can look at its source code and focus on providing AOP.

The code design or framework design always requires the code to be written in a clean and loose way without being dragged.
So a clear design is to plan the running steps step by step from the beginning of the program, and provide some methods for the user to handle in appropriate places. The framework is to place the User box in the self-defined circle, but to give the user as much freedom as possible.
Let's look at the general process of MVC,
1. From the moment you enter the URL and press enter, you can use the urlrouting route to determine which Controller/action the user accesses;
2. Get the specific controller instance through controllerfactory. You can customize the factory.
3. Call action through actioninvoke. You need to obtain the filter of action before calling. These filters are the interceptor of AOP. Users can customize various filters (custom attributes ).
4. Execute action, filter, onactionexecuting, and onactionexecuted in the execution order.
5. Find the view corresponding to the action. You can customize the viewenginer.
6. The rendering page ends.

When an error occurs, invoke's catch calls the implementation of onexception users.

I wanted to list some MVC source code, but I don't feel necessary. Please download it on your own. If you do not know, you can add a group for communication.

This is simple. The idea of AOP is to extract code irrelevant to the current logic. If we pursue the aesthetic of code, we will be more concerned with the overall code design, AOP is usually used for peripheral Building of a system.
The code is more beautiful only when we build beautiful shelves and peripherals.

 

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.