C # Advanced Series--AOP? Aop!

Source: Internet
Author: User
Preface: This article intends to write AOP, speaking of AOP, in fact, Bo master contact this concept only a few months, understand, before they know that many of the original code is based on the principle of AOP, such as the MVC filter filters, which can be caught in the exception of the FilterAttribute, Iexceptionfilter to deal with these two objects, the internal principle of the processing mechanism should be AOP, but there is no such concept.


First, the concept of AOP


The usual, or look at the official explanation: AOP (aspect-oriented programming, aspect-oriented programming), which is a technology that can dynamically and uniformly add functionality to a program without modifying the source code by precompiling and running dynamic proxies. It is a new methodology that complements traditional OOP programming. OOP is concerned with dividing the requirements function into different and relatively independent, well-encapsulated classes, and letting them have their own behavior, relying on inheritance and polymorphism to define each other's relationships; AOP is the ability to separate common requirements functions from unrelated classes, enabling many classes to share a single behavior, once changed , you do not have to modify many classes, but you only need to modify this behavior. AOP is the use of facets (aspect) to modularize crosscutting concerns, and OOP is the use of classes to modularize state and behavior. In the world of OOP, programs are organized through classes and interfaces, and it is appropriate to use them to implement the core business logic of the program. However, it is difficult to achieve crosscutting concerns (functional requirements spanning multiple modules of the application), such as logging, authorization validation, and exception blocking.


Bloggers understand: AOP is to extract the common functions, if the requirements of public functions in the future changes, only need to change the common code of the module, the number of calls where there is no need to change. The so-called aspect-oriented is to focus only on common functionality, not on business logic. The way to achieve this is generally by intercepting. For example, we casually a Web project has the basic permissions to verify the function, in front of each page will verify whether the current login user has permission to view the interface, we can not say in each page of the initialization method to write this verification code, this time our AOP comes in handy, The mechanism of AOP is to pre-define a set of features that have the ability to intercept methods so that you can do the business you want to do before and after executing the method, and we use only the corresponding method or class definition to add a certain feature.


Ii. Advantages of using AOP

Bloggers feel that its advantages are mainly manifested in:

1, the general function from the business logic to pull out, you can omit a large number of duplicate code, conducive to the operation and maintenance of code.

2, in the software design, the extraction of common functions (facets), is conducive to the modularization of software design, reduce the complexity of software architecture. In other words, the general function is a separate module, in the main business of the project is not to see these common features of the design code.

Three, the simple application of AOP

To illustrate how AOP works, bloggers are going to start with a simple example of how AOP works by means of static interception.

1. Static interception

public class order{public int Id {set; get;}    public string Name {set; get;}    public int Count {set; get;}    Public double price {set; get;} public string Desc {set; get;}} public interface iorderprocessor{void Submit (Order order);}    public class orderprocessor:iorderprocessor{public void submit (order order) {Console.WriteLine ("Submit Order");    }} public class orderprocessordecorator:iorderprocessor{public iorderprocessor orderprocessor {get; set;}    Public Orderprocessordecorator (Iorderprocessor orderprocessor) {orderprocessor = Orderprocessor;        } public void Submit (order order) {preproceed (order);        Orderprocessor.submit (order);    Postproceed (order);        public void Preproceed (order order) {Console.WriteLine ("Prior to submitting order data check ...."); if (order. Price 0) {Console.WriteLine ("The Order is in error, please re-check the order.")        "); }} public void Postproceed (order order) {CONSOLE.WRIteline ("After submitting an order, make a log of the orders ..."); Console.WriteLine (DateTime.Now.ToString ("Yyyy-mm-dd HH:mm:ss") + "submit order, Order name:" + order. Name + ", order Price:" + order.    Price); }}

Calling code:

static void Main (string[] args)   {       Order order = New Order () {Id = 1, Name = "Lee", Count = ten, Price = 100.00, De sc = "Order Test"};       Iorderprocessor orderprocessor = new Orderprocessordecorator (new Orderprocessor ());       Orderprocessor. Submit (order);       Console.ReadLine ();   }

Get results:

Above we simulate the order of the example, before submitting an order, we need to do a lot of preparation, such as data validation, etc., after the completion of the order submission, we also need to do logging and so on. The code above is very simple, without any complicated logic, as can be seen from the code above, we have to do the static implantation of the method before and after executing the method to do some of the functions we need. The principle of AOP implementation should be the same, but it helps us to do the method of interception, to save us a lot of duplication of code, we have to do is to write the pre-interception and interception after the need to deal with the logic.


2. Dynamic Agent

Understanding the static interception example, do you have a preliminary understanding of AOP? Below we come to the end of the AOP how to use. According to many cattle in the garden, the way AOP is implemented can be broadly divided into two types: dynamic agent and Il weaving. Bloggers also do not intend to be scripted, respectively, take the demo to speak it. The following two ways to select a representative framework to illustrate.

Dynamic Agent mode, the blogger in the Microsoft Enterprise Library (MS Enterprises) inside the PIAB (Policy Injection Application Block) framework to explain.

You first need to download the following DLLs and then add their references.

Then define the corresponding handler

public class User {public string Name {set; get;}  public string PassWord {set; get;}}     #region 1, define the features to facilitate the use of public class Loghandlerattribute:handlerattribute {public string Loginfo {set; get;}     public int Order {get; set;} public override Icallhandler Createhandler (Iunitycontainer container) {return new Loghandler () {Order = this . Order, Loginfo = this.     Loginfo};     }} #endregion #region 2, register to the required handler interception request public class Loghandler:icallhandler {public int Order {get; set;}      public string Loginfo {set; get;}     This method is the interception method, which can specify the interception public imethodreturn Invoke (imethodinvocation input, Getnexthandlerdelegate GetNext) before and after the execution of the method.         {Console.WriteLine ("Loginfo content" + loginfo); 0. parse parameter var arrinputs = input.         Inputs;         if (Arrinputs.count > 0) {var oUserTest1 = arrinputs[0] as User;         }//1. Intercept Console.WriteLine Before executing the method ("intercept before Method execution");     2. Method of Implementation    var Messagereturn = GetNext () (input, getNext);         3. Interception Console.WriteLine After the execution of the method ("interception of the method after execution");     return messagereturn;     }} #endregion #region 3, user-defined interface and implementation public interface Iuseroperation {void Test (user ouser); void Test2 (user ouser, user oUser2); }//must inherit this class MarshalByRefObject, otherwise error public class Useroperation:marshalbyrefobject, iuseroperation {private Stati     c useroperation ouseropertion = null;     Public useroperation () {//ouseropertion = Policyinjection.create ();         }//define a singleton pattern to policyinjection.create () the resulting object out, so as to avoid writing these things at the call public static Useroperation getinstance () {          if (ouseropertion = = null) Ouseropertion = Policyinjection.create ();     return ouseropertion;      }//Call property also blocks public string Name {set; get;}         [Loghandler], add this attribute on the method, only for this method intercept [Loghandler (loginfo = "Test log is AAAAA")] public void Test (User ouser) {     Console.WriteLine ("Test method executed"); }     [Loghandler (loginfo = "Test2 log is bbbbb")] public void Test2 (user ouser, user oUser2) {Console.writeli     NE ("Test2 method performed"); }} #endregion

Finally, let's look at the code of the call:

static void Main (string[] args) {    try    {        var oUserTest1 = new User () {Name = "test2222", PassWord = "Yxj"};
  var oUserTest2 = new User () {Name = "test3333", PassWord = "Yxj"};        var ouser = Useroperation.getinstance ();        Ouser.test (oUserTest1);        Ouser.test2 (OUSERTEST1,OUSERTEST2);    }    catch (Exception ex)    {        //throw;    }}

The results were as follows:

Let's look at the order in which the test () method and the Test2 () method are executed.

Because the test () and Test2 () methods add the Loghander feature, this feature defines the handler of the AOP, which goes into the Invoke () method before and after the test and Test2 methods are executed. In fact, this is the meaning of AOP, the general function of the section in a unified place to handle, in the main logic directly using the features can be used.


3, IL knitting

The way of static weaving bloggers intend to use Postsharp to illustrate that this is a simple to use, and the other projects used in this way.

Postsharp started charging from the 2.0 version. To illustrate the functionality of AOP, bloggers have downloaded a free version of the installation package, using Postsharp Unlike other frameworks, it is important to download the installation package, only referencing the class library is not possible, because as mentioned above, the AOP framework needs to add extensions for the compiler or runtime. Use the following steps:

(1) Download the POSTSHARP installation package and install it.

(2) Add a reference to the PostSharp.dll DLL in a project that needs to use AOP.

(3) Define the interception method:

[Serializable]public class testaop:postsharp.aspects.onmethodboundaryaspect{//exception occurs when entering this method public    override void O Nexception (Methodexecutionargs args)    {        base. Onexception (args);    } Execute this method before the method public    override void OnEntry (Methodexecutionargs args)    {        base. OnEntry (args);    } This method is executed after the method is executed public    override void OnExit (Methodexecutionargs args)    {        base. OnExit (args);}    }

Note that the TESTAOP of this class must be serializable, so add the [Serializable] feature

(4) Use where the interception function is required.

Add feature interception to the class, and all of the methods below this class will have interception capabilities.

[Testaop]public class impc_tm_plant:ifc_tm_plant  {       ////////] Gets or sets the service interface. //       private ic_tm_plantservice service {get; set;}       Public IList Find ()      {          dto_tm_plant otest = null;          Otest.name_c = "Test";            Exception, it enters the Onexception method return service.      FindAll (); }  }

This method is only intercepted if the method above is blocked by the feature.

[Testaop]public IList Find () {    dto_tm_plant otest = null;    Otest.name_c = "Test";    Return service. FindAll ();}

There is no feeling very simple, very powerful, in fact, this simple application, to solve our common log, exception, authorization and other functions is simply too small a piece of cake. Of course Postsharp may have many more advanced features that are interesting to delve into.

4. Filter in MVC

public class Aopfilterattribute:actionfilterattribute, iexceptionfilter {public      void onexception ( Exceptioncontext filtercontext)     {         throw new system.notimplementedexception ();     }     public override void OnActionExecuting (ActionExecutingContext filtercontext)     {          base. OnActionExecuting (Filtercontext);     }      public override void OnActionExecuted (ActionExecutedContext filtercontext)     {         base. OnActionExecuted (Filtercontext);     } }

Use this feature in the controller:

[Aopfilter]   Public Jsonresult Geteditmodel (string strtype)   {       var lstres = new list> ();       var lstrespage = new List ();  //.........todo        return Json (new {lstdataattr = lstres, pageattr = lstrespage, lstjsconnections = Lstjsplumbli NES}, Jsonrequestbehavior.allowget);   }

debugging shows that before executing the Geteditmodel (string strtype) method, the OnActionExecuting () method is executed before the Geteditmodel (string strtype). The onactionexecuted () method is also executed. This is in our MVC authorization, error page guidance, logging and other common functions can be easily resolved.

The above is the C # Advanced series--AOP? Aop! For more information, please pay attention to topic.alibabacloud.com (www.php.cn)!

  • 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.