Search code examples
c#fallbackpollyretry-logic

Polly: wrap AsyncFallbackPolicy<TResult> with AsyncFallbackPolicy


I want to wrap a combination of AsyncFallbackPolicy <- AsyncFallbackPolicy<bool> <- AsyncRetryPolicy.

Wrapping AsyncFallbackPolicy<bool> <- AsyncRetryPolicy works fine and the resulting PolicyWrap is AsyncPolicyWrap<bool>. But as soon as I add AsyncFallbackPolicy I get the following error:

You have executed the generic .Execute method on a non-generic FallbackPolicy. A non-generic FallbackPolicy only defines a fallback action which returns void; it can never return a substitute TResult value. To use FallbackPolicy to provide fallback TResult values you must define a generic fallback policy FallbackPolicy. For example, define the policy as Policy.Handle.Fallback(/* some TResult value or Func<..., TResult> */);

I execute the policy via await policyWrap.ExecuteAsync(async () => await ...

I couldn't figure out how to resolve this issue. Is it possible to wrap like that? If yes, how?

Thanks


Solution

  • It is not possible to mix generic and non-generic Fallback policies in a PolicyWrap. You should move the behaviour intended for the non-generic AsyncFallbackPolicy into the generic AsyncFallbackPolicy<bool>.

    Explanation: When the AsyncFallbackPolicy<bool> is included in the PolicyWrap, it creates an AsyncPolicyWrap<bool> which can only be used to execute delegates asynchronously returning bool.

    A non-generic AsyncFallbackPolicy cannot participate in an execution asynchronously returning bool for the reasons stated in the error message:

    A non-generic FallbackPolicy only defines a fallback action which returns void; it can never return a substitute TResult value.

    IE If the non-generic AsyncFallbackPolicy was invoked (if the conditions of its Handle clauses were met), it only contains code to asynchronously return void ... but void is not a permissible return value for type bool, so the execution does not make sense ... so Polly does not permit it.