C # advanced series-AOP? AOP!

Source: Internet
Author: User

C # advanced series-AOP? AOP!
Today's big parade, but the hard-pressed bloggers still have to sit in front of the computer and write their blogs. In order to figure out AOP, the bloggers are also fighting hard. I plan to write AOP in this article. Speaking of AOP, it takes only a few months for its real-time bloggers to understand this concept. I learned that many of the Code principles I wrote previously were based on AOP, for example, in the MVC Filter, exception capture can be handled through FilterAttribute and IExceptionFilter. The internal principle of the processing mechanism of these two objects should be AOP, but this concept is not used before. I. the old concept of AOP should first look at the official explanation: AOP (Aspect-Oriented Programming, Aspect-Oriented Programming ), it is a technology that allows you to dynamically and uniformly add functions to programs without modifying the source code through the pre-compilation method and runtime dynamic proxy. It is a new methodology and a supplement to traditional OOP programming. OOP focuses on dividing the required functions into different and relatively independent classes with well-encapsulated classes and allowing them to have their own behaviors and define their relationships based on inheritance and polymorphism; AOP is designed to separate general-purpose functions from irrelevant classes, so that many classes share an action. Once a change occurs, you do not have to modify many classes, you only need to modify this behavior. AOP is the use of aspect to modularize the cross-cutting concerns, while OOP is the use of classes to modularize the status and behavior. In the OOP world, programs are organized through classes and interfaces. It is very appropriate to use them to implement the core business logic of the program. However, it is difficult to achieve cross-cutting concerns (functional requirements that span multiple modules of an application), such as logging, permission verification, and exception interception. Understanding of bloggers: AOP extracts public functions. If the demand for public functions changes in the future, you only need to modify the code of the Public modules, you do not need to change the number of calls. The so-called aspect-oriented approach focuses only on general functions, rather than business logic. The implementation method is generally through interception. For example, the permission verification function is basically available for any Web project. Before entering each page, the system checks whether the current logon user has the permission to view the interface, we cannot say that this verification code is written in the initialization method of each page. At this time, our AOP will be used. The mechanism of AOP is to pre-define a set of features, enable this function to intercept methods and enable you to do the business you want to do before and after the method is executed, we only need to add a feature to the corresponding method or class definition. 2. The advantages of using AOP the bloggers think that their advantages are mainly manifested in: 1. extract common functions from the business logic and omit a large number of repeated codes, it facilitates code operation and maintenance. 2. in software design, general functions are extracted, which facilitates software design modularization and reduces the complexity of the software architecture. That is to say, all common functions are separate modules, and the Design Code of these general functions cannot be seen in the main business of the project. Iii. Simple Application of AOP to illustrate the working principle of AOP, the blogger intends to first understand how AOP works through static interception from a simple example. 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: IOrd ErProcessor {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 ("verify the order data before submitting the order .... "); if (order. price <0) {Console. writeLine ("the total order price is incorrect, please Re-check the order. ") ;}} Public void PostProceed (Order order) {Console. writeLine ("after submitting a ticket, record the order log ...... "); Console. writeLine (DateTime. now. toString ("yyyy-MM-dd HH: mm: ss") + "Submit order, order name:" + order. name + ", order price:" + order. price );}}

 

Call code:
Static void Main (string [] args) {Order order = new Order () {Id = 1, Name = "lee", Count = 10, Price = 100.00, desc = "Order Test"}; IOrderProcessor orderprocessor = new OrderProcessorDecorator (new OrderProcessor (); orderprocessor. submit (order); Console. readLine ();}

 

Expected result: in the preceding example of simulated order submission, we need to make a lot of preparations before submitting an order, such as data validity verification. After the order is submitted, we also need to record logs. The above code is very simple and there is no complicated logic. From the code above, we can see that we can manually execute the method before and after the method is executed through static implantation to let it do some of the functions we need. The implementation principle of AOP should be the same, but it helps us implement method interception and saves us a lot of repetitive code. What we need to do is to write the logic that needs to be processed before and after interception. 2. The dynamic proxy understands the static interception example. Do you have a preliminary understanding of AOP. Next we will discuss how to use AOP. According to many cool people in the garden, the implementation of AOP can be roughly divided into two types: Dynamic proxy and IL weaving. The blogger is not planning to follow the instructions in this article. Let's talk about the Demo separately. The following describes how to select a representative framework in two ways. Dynamic proxy mode, the blogger to Microsoft Enterprise Library (MS Enterprise Library) in the piab (Policy Injection Application Block) framework to explain. Download the following dll files and add their references. Then define the corresponding Handler
Public class User {public string Name {set; get;} public string PassWord {set; get ;}# region 1. Define 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 a public class LogHandler: ICallHandler {public int Order {get; set;} public string LogInfo {set; get;} // This method is the interception method. It can be used to intercept public IMethodReturn Invoke (IMethodInvocation input, GetNextHandlerDelegate getNext) {Console. writeLine ("LogInfo content" + LogInfo); // 0. the parsing parameter var arrInputs = input. inputs; if (arrInputs. count> 0) {var oUserTest1 = arrInputs [0] as User;} // 1. the interception Console before the method is executed. writeLine ("intercepted before method execution"); // 2. run var messagereturn = getNext () (input, getNext); // 3. the interception Console after the method is executed. writeLine ("intercepted after method execution"); return messagereturn ;}# endregion # region 3. User-Defined interface and implementation of public interface IUserOperation {void Test (User oUser ); void Test2 (User oUser, User oUser2);} // This class must be inherited here; otherwise, the public class UserOperation: Implements albyrefobject, IUserOperation {private static UserOperation oUserOpertion = null is reported; public UserOperation () {// oUserOpertion = PolicyInjection. create <UserOperation> () ;}// defines the singleton mode and sets PolicyInjection. create <UserOperation> () generates this object, which avoids writing these items in the call. public static UserOperation GetInstance () {if (oUserOpertion = null) oUserOpertion = PolicyInjection. create <UserOperation> (); return oUserOpertion;} // The call property also blocks public string Name {set; get ;}// [LogHandler]. Add this property to the method, only [LogHandler (LogInfo = "Test log is aaaaa")] public void Test (User oUser) {Console. writeLine ("the Test method is executed");} [LogHandler (LogInfo = "the log of Test2 is bbbbb")] public void Test2 (User oUser, User oUser2) {Console. writeLine ("Test2 method executed") ;}# endregion

 

Finally, let's look at the called code:
        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 result is as follows: Let's look at the order in which the Test () method and Test2 () method are executed. Because the LogHander feature is added to the Test () and Test2 () methods, this feature defines the AOP Handler. Before and after the Test and Test2 methods are executed, the Invoke () method. In fact, this is the significance of AOP. We can process the common functions of the aspect in a unified place and directly use the features in the main logic. 3. the blogger intends to use PostSharp to describe the static weaving mode of IL weaving. This method is easy to use and is also used in the project. Postsharp has been charged since version 2.0. To describe the function of AOP, the blogger downloads an installation package in the free version. If PostSharp is not the same as other frameworks, you must download the installation package and install it, as mentioned above, the AOP framework needs to add extensions for the compiler or runtime. The steps are as follows: (1) download the Postsharp installation package and install it. (2) Add a reference to the dll PostSharp. dll in the project where you need to use AOP. (3) define interception methods:
[Serializable] public class TestAop: PostSharp. aspects. onMethodBoundaryAspect {// when an exception occurs, enter this method public override void OnException (MethodExecutionArgs args) {base. onException (args);} // execute this method public override void OnEntry (MethodExecutionArgs args) {base. onEntry (args);} // After the method is executed, execute this method public override void OnExit (MethodExecutionArgs args) {base. onExit (args );}}

 

Note that the TestAop class must be Serializable. Therefore, you must add the [Serializable] feature (4) to use the Interception Function. Add feature interception to the class. All methods below this class will have the Interception Function.
[TestAop] public class Impc_TM_PLANT: Ifc_TM_PLANT {// <summary> // gets or sets the service interface. /// </Summary> private Ic_TM_PLANTService service {get; set;} public IList <DTO_TM_PLANT> Find () {DTO_TM_PLANT otest = null; otest. NAME_C = "test"; // exception, the OnException method return service will be entered. findAll ();}}

 

This method only intercepts this method.
        [TestAop]        public IList<DTO_TM_PLANT> Find()        {            DTO_TM_PLANT otest = null;            otest.NAME_C = "test";            return service.FindAll();        }

 

Is it very simple and powerful? In fact, this simple application is just a piece of cake to solve common functions such as logs, exceptions, and permission verification. Of course, Postsharp may have many more advanced functions. If you are interested, you can go further. 4. Filter public class AOPFilterAttribute in MVC: 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 controller:
     [AOPFilter]        public JsonResult GetEditModel(string strType)        {            var lstRes = new List<List<DragElementProp>>();            var lstResPage = new List<PageProperty>();        //.........todo            return Json(new { lstDataAttr = lstRes, PageAttr = lstResPage, lstJsConnections = lstJsPlumbLines }, JsonRequestBehavior.AllowGet);        }

 

Debugging shows that before the GetEditModel (string strType) method is executed, the OnActionExecuting () method is executed, and the OnActionExecuted () method is executed after the GetEditModel (string strType) method is executed. This can be easily solved by common functions such as permission verification, error page orientation, and logging in MVC.

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.