C# 使用Polly的重试侦听器不适用于Unity

C# 使用Polly的重试侦听器不适用于Unity,c#,unity-container,polly,C#,Unity Container,Polly,我正在使用Microsoft Unity v5.8.6和Polly v7.1.0。 我的要求是我需要触发一个按钮的基础上点击电子邮件。由于某些原因,如果sendEmail失败,我需要重试“x”次 RetryOneExceptionAttribute.cs RetryInterceptor.cs 单位配置 container.RegisterType(新TransientLifetimeManager(),新拦截器(),新拦截器行为()); 除了Policy.Handle().WaitAndRe

我正在使用Microsoft Unity v5.8.6和Polly v7.1.0。 我的要求是我需要触发一个按钮的基础上点击电子邮件。由于某些原因,如果sendEmail失败,我需要重试“x”次

RetryOneExceptionAttribute.cs

RetryInterceptor.cs

单位配置

container.RegisterType(新TransientLifetimeManager(),新拦截器(),新拦截器行为());
除了Policy.Handle().WaitAndRetry之外,一切都正常工作。发生异常时,它不会重试,而是返回结果。 我不确定我错过了什么


提前感谢

您需要在polly的
中重新显示异常。执行
处理程序。请尝试以下代码

  .Execute(() => {
       result = getNext()(input, getNext);
       if (result.Exception != null) {
          throw new Exception("Retry", result.Exception);
       }
  });
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;
    }

}
 [RetryOnException(3, 1)]
    public void SendEmail(NotificationRequest request)
    {
container.RegisterType<INotificationService, Services.NotificationService>(new TransientLifetimeManager(),new Interceptor<InterfaceInterceptor>(), new InterceptionBehavior<RetryInterceptor>());
  .Execute(() => {
       result = getNext()(input, getNext);
       if (result.Exception != null) {
          throw new Exception("Retry", result.Exception);
       }
  });