What is?AOP? Quote Baidu Encyclopedia:AOP byAspect Oriented Programming Abbreviation, Meaning for: Face to face programming
, A technology of unified maintenance of program functions by precompiling and dynamic agent in runtime. RealizationAOP There are two main ways, One is compile time static seeding, The advantage is high efficiency, The disadvantage is the lack of flexibility,.net lowerpostsharp Representative( This is for a fee). Another way is dynamic proxy, Advantages and disadvantages are opposite to the former, Dynamically create agents for target types, Interception through proxy calls.AOP What can be done, A common use case is transaction processing, Logging, etc. Let's talk about itAutofac How to achieveAOP,Autofac It is a.net Excellent, Very good performanceIOC container(.net The most efficient container), AddAOP It's just like adding wings to the tiger.Autofac OfAOP It is throughCastle( It's also a container) Core part of the project
Realized, be known asAutofac.Extras.DynamicProxy, Seeing the name of a thing one thinks of its function, Its implementation mode is dynamic agent.


   Preparation before use:

     adoptNuget Install package :Autofac,Autofac.Extras.DynamicProxy, Three references will be added after successful installation

    

   Now it's officially started!

 

   First step: Create interceptor

   Here is a simple example of an interceptor, The function of the interceptor is to display the name of the intercepted method, Parameter list and return results

  
1 /// <summary> 2 /// Interceptor Need to achieve IInterceptor Interface Intercept Method 3 /// </summary>
4 public class CallLogger: IInterceptor 5 { 6 TextWriter _output; 7 8
public CallLogger(TextWriter output) 9 { 10 _output = output; 11 } 12 13 ///
<summary> 14 /// interceptor method Print the name of the blocked method before execution, After parameters and methods are executed Return result 15 /// </summary> 16 ///
<param name="invocation"> Contains information about blocked methods</param> 17 public void
Intercept(IInvocation invocation)18 { 19 20 _output.WriteLine(" You are calling a method \"{0}\"
Parameter is {1}...", 21 invocation.Method.Name, 22 string.Join(", ",
invocation.Arguments.Select(a => (a ??"").ToString()).ToArray())); 23 24 //
After the intercepted method is executed Continue execution 25 invocation.Proceed(); 26 27 _output.WriteLine("
Method execution completed, Return result:{0}", invocation.ReturnValue); 28 } 29 }
 

   The second step: Register interceptor toAutofac container

   Interceptors must be registered toAufofac Container, It can be injected by interceptor type or naming, These two ways make the use of interceptors different( I'll talk about it later).

  
1 // Nomenclature injection 2 builder.Register(c => new CallLogger(Console.Out)) 3
.Named<IInterceptor>("log-calls"); 4 5 // Type injection 6 builder.Register(c => new
CallLogger(Console.Out));
   The third step: Enable interceptor

   There are two main ways to enable interceptors:EnableInterfaceInterceptors(),EnableClassInterceptors().

  EnableInterfaceInterceptors Method creates an interface proxy dynamically

  EnableClassInterceptors Method creates a subclass proxy class of the target class, It should be noted that only virtual methods can be intercepted, override method

   Enable interceptor sample code:

  
// Enable class agent interception builder.RegisterType<Circle>().EnableClassInterceptors(); // Enable interface agent interception
builder.RegisterType<Circle>().EnableInterfaceInterceptors();
   The fourth step: Indicates the type to intercept

   There are two ways:

     First kind: Add properties to typesAttribute

    

     Second kinds: Dynamically inject interceptors when registering types to containers

    
1 // Dynamic injection interceptorCallLogger 2 builder.RegisterType<Circle>().InterceptedBy(typeof
(CallLogger)).EnableClassInterceptors();
   The fifth step: Test results

    1. Class agent interception

    

    Circle Class code:

    

     2. Interface agent interception

    

     IShape Interface code:

    
1 public interface IShape 2 { 3 /// <summary> 4 /// Area of shape 5 /// </summary> 6
void Area(); 7 8 }
    Circle Class code:

    
1 public class Circle:IShape 2 { 3 // Override parent class abstract methods 4 public void Area() 5 { 6
Console.WriteLine(" You are calling the circle area method"); 7 } 8 }
 

     If there is something wrong, please correct it, If you have any questions, Welcome questions.