簡體   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