我正在使用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
外,其他所有功能均按预期工作。发生异常时,它不会重试,而是返回结果。
我不确定我缺少什么。
预先感谢
答案 0 :(得分:1)
您需要在polly的.Execute
处理程序中重新抛出异常。请尝试以下代码
.Execute(() => {
result = getNext()(input, getNext);
if (result.Exception != null) {
throw new Exception("Retry", result.Exception);
}
});