Introduction to AOP oriented tangent programming

Source: Internet
Author: User

The word AOP believes that we have not touched too much, but in fact you are already in touch, in design mode. The idea used by AOP is the same as the design pattern, which is to add or modify functions uniformly without modifying the original code. Also, AOP is mostly used in spring, but this article is written only in MVC application, be aware of.


First, Introduction


The so-called AOP (Aspect oriented programming abbreviation) means

face to Section of the compilation Process , a technology that implements the unified maintenance of program functions by means of precompilation and runtime dynamic agent. AOP is a continuation of OOP, a hotspot in software development, an important content in the spring framework, and a derivative model of functional programming. AOP enables the isolation of parts of the business logic, which reduces the coupling between parts of the business logic, improves the reusability of the program, and improves the efficiency of development.

The above is the official explanation of Baidu Encyclopedia, but in my opinion, in fact, AOP is more a kind of thought, a kind of thought that can move and pass through the whole body, AOP actually face more is a kind of consent function or call process to write a program body, From its first word aspect (facets) also refers to an aspect, it can also be understood that this approach is the implementation of an aspect, which is actually similar to the global file in MVC , is also an important part of the spring framework, is a derivative paradigm of functional programming. AOP enables the isolation of parts of the business logic, which reduces the coupling between parts of the business logic, improves the reusability of the program, and improves the efficiency of development.

The second is that its pre-compilation nature can be very good to deal with some errors or pre-judgment of some cases, which also led to it in the design of the time to judge the authority, the unified output of something is more common. " the ability to dynamically and uniformly add functionality to a program without modifying the source code can be achieved through precompilation and run-time dynamic proxies." AOP is actually a continuation of the GOF design pattern, and the design pattern pursues the decoupling between the caller and the callee, improving the flexibility and extensibility of the code, and AOP can be said to be an implementation of this goal. "The above statement is also a good interpretation of AOP.


second, the implementation in the MVC


Say so much, let's do the actual combat, first we need to create a new MVC project in VS, choose MVC3 or 4 OK, and then build a controller, name casual, then build his view, the view is written on the simplest HelloWorld.


<! DOCTYPE html>


The image on the right is the MVC solution I created and the added controller and view that write the above code in view to show hello! World.

After running (will not run self-Baidu) is not on the display of a HelloWorld word on the page?

Okay, so let's start with a new AOP file and then use it, first adding a new class to this project, called Filterpublic, and adding a using SYSTEM.WEB.MVC reference where it's referenced, Then let this class inherit from the ActionFilterAttribute, we should pay attention to the word action, which means that this thing is based on action.

We then write the following code:


        public string Message {get; set;} public override void OnActionExecuting (ActionExecutingContext filtercontext) {base.            OnActionExecuting (Filtercontext);        FilterContext.HttpContext.Response.Write ("Before action executes" + Message + "<br/>"); } public override void OnActionExecuted (ActionExecutedContext filtercontext) {base.            OnActionExecuted (Filtercontext);        FilterContext.HttpContext.Response.Write ("After action executes" + Message + "<br/>"); } public override void Onresultexecuting (ResultExecutingContext filtercontext) {base.            Onresultexecuting (Filtercontext);        FilterContext.HttpContext.Response.Write ("return result before" + Message + "<br/>"); } public override void Onresultexecuted (ResultExecutedContext filtercontext) {base.            Onresultexecuted (Filtercontext); FilterContext.HttpContext.Response.Write ("After return result" + Message + "< br/> "); }

This is the filter triggered by the various actions, and then we in the controller inside the default method to make the following changes:


        [filterpublic(Message = "Action")]        Public ActionResult Index ()        {            HttpContext.Response.Write ("Action is executing ... <br/> ");            Return Content ("Returning result <br/> ");        }

Then add a sentence to the Controller class (Filterpublic(Message = "Controller"), and then run, what will happen?

Actionaction is executing before action executes ... Action is returning result after action executes after action returns result Returns the action after result


You can see that the controller's methods are executed before executing the following set offilterpublic inside the code, and as the inside of the action occurs in different time can also be seen which method is triggered.

But the controller-based method written on the controller does not trigger, why?

In fact, the problem is simple, that is, when we set up our AOP program, we did not set the parameters, we did not let filter to stack the run, this time we just add the Filterpublic class: [AttributeUsage ( AttributeTargets.All, AllowMultiple = True)], you can set the various filter or overlay filter to trigger, this time we run again try:


Actionaction is executing before the action executes before Controlleraction executes ... The action is returning result before the controller returns result after the action executes after Actionaction executes. After the action returns result, the Controller

As a result, the filter on the controller is also triggered, so we only need to write a filter class label on our own method of writing or on the default loading method of the page.

So wouldn't it be a hassle if we had a function that required all the pages to be triggered? Don't worry, it's time for our global file to work. Under the Registerglobalfilters method below the Global.asax file, register your own filter to write:


public static void Registerglobalfilters (Globalfiltercollection filters) {    filters. ADD (New Handleerrorattribute ());    Define your filter as a global filter    filterpublic() {Message = "global <br/>"});}

Then run and look at the results:


The action executes before the global action executes before the controlleraction executes actionaction is executing ... The action is returning result after the action executes after the actionaction executes controlleraction after the global return result before the global returned result before the controller returns the result. Returns the result after the action returns result after the controller returns the global

So the global trigger is done (the message in filter is only used to identify the hierarchy, and it can be used without a definition.) )


In this case, if you want to quickly add a global use of the method, just need to create a new filter, and then change the global file can be done, is not very convenient.


The above are some of my shallow research on AOP, if the wrong place also ask the reader to correct.

Introduction to AOP oriented tangent programming

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.