围绕 Polly 框架进行包装,以便实现可以停留在一个地方 [英] Wrapper around Polly Framework so that implementation can stay at a single place

查看:60
本文介绍了围绕 Polly 框架进行包装,以便实现可以停留在一个地方的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经浏览了 Polly Framework 的文档和示例,它真的很棒而且使用起来很简单!!

I have gone through the documentation and examples of Polly Framework, and it's really awesome and simple to use !!

就我而言,我想将所有异常分为 3 种类型:临时、永久和日志.现在,我想要一段代码,负责通过使用 Polly 框架进行等待和重试来处理本质上是临时的错误.

In my case, I want to classify all the exceptions into 3 types: temporary, permanent and log. Now, I want to have a single piece of code which will be responsible to handle errors which are temporary in nature by doing wait and retry using Polly Framework.

  WaitAndRetryAsync(new[]{
                    TimeSpan.FromSeconds(1),
                    TimeSpan.FromSeconds(2),
                    TimeSpan.FromSeconds(5)
                  })

同样,如果某些东西本质上是永久性的(应该能够根据我们尝试处理的异常知道它的类型,例如:超时可以是临时的,但如果数据库信用不正确,则它是永久性的)然后我们可以发送电子邮件给支持人员.

Same way, if something is permanent in nature (should be able to know it's type based on the exception we are trying to handle example: timeout can be interim but if database cred are not correct then it's permanent) then we can send email to the support staff.

现在,问题从这里开始,我如何使用接口或抽象类包装它,以便我的所有派生类都可以传递一个异常以及方法名称,该异常可以传递给我的新框架和它会做需要的.

Now, the problem starts here that, how I can wrap it using an interface or Abstract class so that my all the derived class can pass on an exception along with method name, which can be passed on to my new framework and it will do the needful.

任何指针都会有很大帮助!

Any pointers will be of great help !

推荐答案

您可以创建一个接受 FuncAction 到您希望 Polly 调用的代码的类.

You could create a class that accepts a Func or Action to the code you want Polly to call.

类似于这个辅助方法:

public class RetryWrapper
    {
        public static TOutput Execute<TInput, TOutput>(Func<TInput, TOutput> func, TInput input)
        {
            RetryPolicy retryPolicy = Policy.Handle<TimeoutException>()
                .Or<OtherException>()
                .WaitAndRetry(3, x => new TimeSpan(0, 0, 2));

            return retryPolicy.Execute(() => func(input));
        }
    }

然后你可以调用它

var result = RetryWrapper.Execute<string, bool>(x => MethodToCall(x), "input")

这篇关于围绕 Polly 框架进行包装,以便实现可以停留在一个地方的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆