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

问题描述 投票:1回答:1

我正在使用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)
    {

UnityConfiguration

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

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

提前致谢

c# unity-container polly
1个回答
1
投票

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

  .Execute(() => {
       result = getNext()(input, getNext);
       if (result.Exception != null) {
          throw new Exception("Retry", result.Exception);
       }
  });
© www.soinside.com 2019 - 2024. All rights reserved.