What is AOP? Quoting Baidu Encyclopedia: AOP is the abbreviation of Aspect Oriented Programming, which means: a technology for face-oriented programming to achieve unified maintenance of program functions through pre-compilation methods and dynamic agents during runtime. There are two main ways to implement AOP, one is static implantation at compile time, the advantage is high efficiency, the disadvantage is lack of flexibility, and postsharp under .net is the representative (this is charged). The other method is dynamic proxies, which have the opposite advantages and disadvantages of the former, dynamically creating proxies for the target type and intercepting them through proxy calls. What AOP can do, common use cases are transaction processing, logging, etc. Let's talk about how Autofac implements AOP, Autofac is a very good IOC container under .net and very good performance (the most efficient container under .net), plus AOP is simply a tiger. Autofac's AOP is implemented through the core part of the Castle (also a container) project called Autofac.Extras.DynamicProxy, which, as the name suggests, is implemented as a dynamic proxy.
Preparation before use:
Install the Nuget package Autofac, Autofac.Extras.DynamicProxy, and three references will be added after successful installation
Now it's officially started!
Step 1: Create an interceptor
Below is an example of a simple interceptor that displays the name of the intercepted method, a list of parameters, and the return result
Step 2: Register the interceptor to the Autofac container
The interceptor must be registered in the Aufofac container, either by interceptor type or by name, which makes the method of using the interceptor different (as discussed later).
Name injection builder. Register(c => new CallLogger(Console.Out)). Named<IInterceptor>("log-calls");
Type injection builder. Register(c => new CallLogger(Console.Out));
Step 3: Enable the interceptor
There are two main ways to enable the interceptor: EnableInterfaceInterceptors(), EnableClassInterceptors().
The EnableInterfaceInterceptors method dynamically creates an interface proxy
The EnableClassInterceptors method will create a subclass proxy class of the target class, and it should be noted here that it will only intercept the virtual method and override the method
Enable Interceptor sample code:
Step 4: Indicate the type you want to intercept
There are two ways:
The first type: Add a feature attribute to the type
The second type is to dynamically inject the interceptor when the registration type is transferred to the container
Step 5: Test the effect
1. Proxy interception
Circle class code:
2. Interface proxy interception
IShape Interface Code:
Circle class code:
|