Aspnetcore implementation of Polly based on AOP

Source: Internet
Author: User

Preface  

Speak Up AOP, in fact, we should do mvc/api when there should be no less contact, for example, all kinds of fitter is a typical AOP.

originally in use Polly I was originally intended to use the filter to achieve, and later found to be quite difficult to achieve, the use of netcore in the middle and filter to achieve an AOP independent application services It's just, I'm a little helpless, quite difficult to write.

And then it was used, AUTOFAC is a little weak to do interceptors. The estimates are still too weak.

Now I've learned that the implementation Polly the more convenient third-party AOP framework has

(1),Aspectcore: is a aspnetcore lightweight AOP solution.

(2),dora.interception old a write an AOP solution, this use in the solution will need to wait until the old a upgrade next edition.

filters in the aspnetcore:

when using The main point of policy is the formulation of policies, and the use of AOP is the most appropriate solution in cases where the code is clean and does not break the current code logic.

when we use the filter we will find that Pollicy has developed an error rule and uses it in the error filter and does not fetch any error messages, because the error message is fetched by the error filter and does not trigger Pollicy

and try. using filtering to achieve a when a program error occurs, the function of another method is executed, similar to Policy's retry policies or demotion.

The following code:

Write: A filter class:

usingMICROSOFT.ASPNETCORE.MVC;usingMicrosoft.AspNetCore.Mvc.Filters;usingSystem;usingSystem.Reflection;namespaceinterceptorcorelibrary{[AttributeUsage (AttributeTargets.Class|AttributeTargets.Method)] Public classCoreexceptionfilter:attribute, Iexceptionfilter,iactionfilter {/// <summary>        ///how to re-execute when an error occurs/// </summary>         Public stringFallbackclass {Get;Set; } /// <summary>        ///how to re-execute when an error occurs/// </summary>         Public stringFallbackmethod {Get;Set; } /// <summary>        ///gets the parameters of the method/// </summary>         Public Object[] Invokeparameters {Get;Set; } /// <summary>        ///The constructor uses this class when the argument is a method/// </summary>        /// <param name= "Fallbackmethod" ></param>         PublicCoreexceptionfilter (stringFallbackclass,stringFallbackmethod) {             This. Fallbackmethod =Fallbackmethod;  This. Fallbackclass =Fallbackclass; }        /// <summary>        ///using the new method/// </summary>        /// <param name= "asm" ></param>        /// <param name= "parameters" ></param>        /// <returns></returns>        Private ObjectUsenewmethod (Assembly ASM,Object[] Parameters) {Object obj=NULL; foreach(Type typeinchASM. Getexportedtypes ()) {if(Type. Name = =Fallbackclass) {obj=System.Activator.CreateInstance (type); foreach(varIteminchtype. GetMethods ()) {if(item. Name = =Fallbackmethod) {obj=type. GetMethod (Fallbackmethod).                        Invoke (obj, parameters); }                    }                }            }            returnobj; }        /// <summary>        ///get parameters for all monitored methods/// </summary>        /// <param name= "context" ></param>         Public voidonactionexecuting (ActionExecutingContext context) {Object[] Parameters =New Object[Context.            Actionarguments.count]; intCount =0; foreach(varIteminchcontext. actionarguments) {Parameters[count]=item.                Value; Count++; } invokeparameters=parameters; }        /// <summary>        ///the wrong time to execute the new method/// </summary>        /// <param name= "context" ></param>         Public voidonexception (Exceptioncontext context) {varObjectresult = context. Exception asException; if(Objectresult.message! =NULL)            {                //context. Result = new Objectresult (Usenewmethod (this. GetType (). Assembly, Invokeparameters));Context. Result =NewObjectresult (New{Success =true, code = $, msg ="Success", Data = Usenewmethod ( This. GetType ().            Assembly, Invokeparameters)}); }        }         Public voidonactionexecuted (ActionExecutedContext context) {} }}

used in the controller:

[Coreexceptionfilter (Nameof (Usermodel), nameof (Delete)])    When executing I throw an exception message    [Coreexceptionfilter ( Nameof (Usermodel), nameof (delete        ))//  Delete api/values/5        [Httpdelete ( " {ID} " )]        publicint Delete (int  ID)        {            throw  New  Exception ();        }
execute another method when the method performs an error:as follows: Note the same parameters:
usingSystem;usingSystem.Collections.Generic;usingSystem.Text;namespaceinterceptorcorelibrary{ Public classUsermodel { Public intDelete (intID) {//Record Log//re-execute the code again            returnID; }    }}
Execution Result:

return Result:

at this point, we can see that the filter grabbed the error message first, Policy will not be caught, but it also implements the downgrade function.

If we do not use The AOP words are written directly in the controller

For example , if you write one or two more lines, the code is quite messy.

 //DELETE API/VALUES/5[Httpdelete ("{ID}")]         Public intDelete (intID) {varPolicyexecute = Policy.handle<exception> (). Fallback (() =              {                  //program error re-executing a new methodUsermodel Usermodel =NewUsermodel ();             Usermodel.delete (ID);                        }); //ExecutionPolicyexecute.execute (() =            {                                Throw NewException ();        }                           ); }

Although the above code does not implement policy, it also demonstrates the principle of using AOP to implement policy in general.

implementing policy with Aspectcore

Here is a copy of Yang Zhengko teacher in the popularization of Aspnetcore Micro-service Course code: Support for the original,

The complete code has been posted here:

Http://www.cnblogs.com/qhbm/p/9228238.html

implementing Policy with dora.interception

I did a simple implementation in the demo: Here is not posted, because the framework is not very perfect, I asked the author of the old A, to wait until the next version of the project is more secure. You can look at the old a blog.

Explain the differences between the two frameworks, which can be used as appropriate, depending on the framework:

There is a lack of hope that we will learn from each other,

This article original: reprint please indicate the source thank you!

Aspnetcore implementation of Polly based on AOP

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.