Understanding and realization of AOP

AOP: Aspect Oriented Programming, without damage to the original code, to provide new functionality. AOP can be used to add common functionality, such as transaction logs, privileges, exceptions, cache ...

 

Common AOP:

MVC in the filter, HttpModule ...

 

How to implement AOP:

1, Decorator, Decorator object is dynamically expanding new features, and does not modify the original class, so it is regarded as AOP, but the high cost (static)

2, the use of dynamic proxy, dynamically created objects. (dynamic)

3, DI frame, since the objects are created by the container, it is easy to implement AOP

 

Case 1, to achieve dynamic proxy AOP:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 using Castle.DynamicProxy;//Castle.Core
 8 
 9 namespace MyAOP
10 {//业务类接口
11         public interface IUserProcessor
12         {
13             void RegUser(User user);
14         }
15     //业务类
16          public  class UserProcessor: IUserProcessor
 . 17          {
 18 is              ///  <Summary> 
. 19              /// must bring Virtual
 20 is              ///  </ Summary> 
21 is              ///  <param name = "User"> </ param> 
22 is              public  Virtual  void RegUser (the user user)
 23 is              {
 24                  Console.WriteLine ($ " registered user .Name: {} user.name, PassWord: user.password {} " );
 25              }
 26 is          }
 27      // the AOP logic 
28          public class MyInterceptor : IInterceptor
29         {
30             public void Intercept(IInvocation invocation)
31             {
32                 PreProceed(invocation);
33                 invocation.Proceed();
34                 PostProceed(invocation);
35             }
36             public void PreProceed(IInvocation invocation)
37             {
38                 Console.WriteLine("方法执行前");
39             }
40 
41             public voidPostProceed (IInvocation Invocation)
 42 is              {
 43 is                  Console.WriteLine ( " After the implementation of the method " );
 44              }
 45          }
 46 }
1 var interceptor = new MyInterceptor();
2                 UserProcessor userprocessor = new ProxyGenerator().CreateClassProxy<UserProcessor>(interceptor);
3                 userprocessor.RegUser(new User
4                 {
5                     Name = "aaa",
6                     Password = "123456"
7                 });

 

 

Guess you like

Origin www.cnblogs.com/fanfan-90/p/12032152.html