Я работаю с 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;
}
}
Я украсил метод sendMail в NotificationService.класс cs с атрибутом
[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
.Когда возникло исключение, оно не повторяет попытку, а возвращает результат.Я не уверен, что мне не хватает.
Заранее спасибо