繁体   English   中英

使用 Polly 重试拦截器不适用于 Unity

[英]Retry Interceptor using Polly is not working for Unity

我正在使用 Microsoft Unity v5.8.6 和 Polly v7.1.0。 我的要求是我需要根据一键单击触发电子邮件。 出于某种原因,如果 sendEmail 失败,我需要重试“x”次。

RetryOnExceptionAttribute.cs

[AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = true)]
public class RetryOnExceptionAttribute : Attribute
{
    public int MaxAttempts { get; set; }
    public int RetryDelay { get; set; }

    public RetryOnExceptionAttribute(int maxAttempts,int retryDelay)
    {
        MaxAttempts = maxAttempts;
        RetryDelay = retryDelay;
    }

}

RetryInterceptor.cs

public class RetryInterceptor : IInterceptionBehavior
{
    public bool WillExecute { get { return true; } }

    public RetryInterceptor()
    {

    }
    public IEnumerable<Type> GetRequiredInterfaces()
    {
        return Type.EmptyTypes;
    }

    public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
    {
        var attrClass = input.MethodBase.GetCustomAttributes(typeof(RetryOnExceptionAttribute), true);
        RetryOnExceptionAttribute retryOnException;
        IMethodReturn result = null;
        if (!attrClass.Any())
        {
            result = getNext()(input, getNext);
            return result;
        }
        else if (attrClass.Any())
        {
            try
            {
                retryOnException = (RetryOnExceptionAttribute)attrClass[0];
                int maxAttempsts = retryOnException.MaxAttempts);
                int maxRetryDelay = retryOnException.RetryDelay;
                Policy.Handle<Exception>().WaitAndRetry(maxAttempsts, retryAttempt => TimeSpan.FromSeconds(maxRetryDelay), (exception, timespan, retryCount, context) =>
                {
                    Console.WriteLine($"Class: {input.Target}, Method: {input.MethodBase}, Retry Count:{retryCount}, Exception {exception.GetCompleteMessage()}");

                }).Execute(() => { result = getNext()(input, getNext); }); /*I am thinking something needs to be changed in Execute() method*/
            }
            catch (Exception)
            {

            }
        }

        return result;
    }

}

我在 NotificationService.cs 类中用属性装饰了 sendMail 方法

 [RetryOnException(3, 1)]
    public void SendEmail(NotificationRequest request)
    {

统一配置

container.RegisterType<INotificationService, Services.NotificationService>(new TransientLifetimeManager(),new Interceptor<InterfaceInterceptor>(), new InterceptionBehavior<RetryInterceptor>());

除了Policy.Handle<Exception>().WaitAndRetry之外,一切都按预期工作。 发生异常时,它不会重试,而是返回结果。 我不确定我错过了什么。

提前致谢

您需要在 polly 的.Execute处理程序中重新抛出异常。 请尝试以下代码

  .Execute(() => {
       result = getNext()(input, getNext);
       if (result.Exception != null) {
          throw new Exception("Retry", result.Exception);
       }
  });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM