What is? AOP? Quote Baidu Encyclopedia :AOP by Aspect Oriented Programming Abbreviation of , Means : Face to face programming
, A technology of unified maintenance of program functions by precompiling and dynamic agent in runtime . realization AOP There are two main ways , One is compile time static seeding , The advantage is high efficiency , The disadvantage is the lack of flexibility ,.net lower postsharp Represented by ( 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 it Autofac How to achieve AOP,Autofac It's a .net Excellent , Very good performance IOC container (.net The most efficient container ), add AOP It's just like adding wings to the tiger .Autofac Of AOP Yes Castle( It's also a container ) Core part of the project
Realized , be known as Autofac.Extras.DynamicProxy, seeing the name of a thing one thinks of its function , Its implementation mode is dynamic agent .


   Preparation before use :

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

    

   Now it's officially started !

 

   Step 1 : 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 implement 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 results 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 results :{0}", invocation.ReturnValue); 28 } 29 }
 

   Step 2 : Register interceptor to Autofac container

   Interceptors must be registered to Aufofac In 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 // Named 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));
   Step 3 : 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();
   Step 4 : Indicates the type to intercept

   There are two ways :

     The first : Add properties to types Attribute

    

     The second : Dynamically inject interceptors when registering types to containers

    
1 // Dynamic injection interceptor CallLogger 2 builder.RegisterType<Circle>().InterceptedBy(typeof
(CallLogger)).EnableClassInterceptors();
   Step 5 : 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 to ask .