AOPFramework Basics
Knowledge required to understand: AOP, Filter, Reflection (Attribute).
If you use Polly directly, you will create a mix of business-agnostic code in your business code. We encapsulate a simple framework that mimics the Hystrix in Spring cloud by using AOP (if you don't know about AOP, refer to the online material yourself).
You need to introduce an AOP that supports. NET core, and we use the AOP framework under. NET Core as Aspectcore (native, dynamic weave), or not support. NET core, or not support the interception of an MVC Filter on an async method.
Github:https://github.com/dotnetcore/aspectcore-framework
Install-package aspectcore.core-version 0.5.0
Here are just a few of our related uses:
1, write interceptors Custominterceptorattribute generally inherit from Abstractinterceptorattribute
Public classcustominterceptorattribute:abstractinterceptorattribute{//executed in each intercepted method Public Async OverrideTask Invoke (aspectcontext context, aspectdelegate next) {
Try{Console.WriteLine ("before executing");
awaitNext (context);//execution of intercepted methods}Catch(Exception) {Console.WriteLine ("An exception occurred in the method being intercepted");
Throw; }finally{Console.WriteLine ("after execution"); }}}
2. Write classes that need to be intercepted by agents
Mark the Custominterceptorattribute on the method to be intercepted. The class needs to be a public class, and the method supports asynchronous methods if interception is a virtual method, because dynamic proxies are implemented dynamically to generate dynamic subclasses of the Proxied class.
class person{ [custominterceptor] publicvoid Say (string msg) { Console.WriteLine ("service calling ... "+msg);} }
3. Create proxy objects through Aspectcore
Newusing (iproxygenerator proxygenerator = proxygeneratorbuilder.build ()) { = Proxygenerator.createclassproxy<person>(); P.say ("rupeng.com");} Console.readkey ();
Note that the object that P points to is the object of the dynamic subclass of the person that the aspectcore generates, and the direct new person cannot be intercepted.
Study AOP Details
The meaning of the properties of the parameter Aspectcontext under the Invoke method in the Interceptor:
Implementation objects that are actually dynamically created by the person subclass.
Implementationmethod is the say method of the person sub-class
The parameter value of the Parameters method.
Proxy==implementation: Under current scenario
Proxymethod==implementationmethod: Under current scenario
ReturnValue return value
Servicemethod is the say method for person
Note: This article is the second edition of the. NET Core MicroServices second Edition and. NET core microservices that I see Yang Zhengko teacher.
(6) ASP. NET core microservices micro-service----AOP Framework