5. Improving Policy Execution with Information from the Caller Flashcards
What is the Polly Context
?
It’s a class which we can use to pass information from the caller into the policies.
What key class does the Polly Context
inherit from, giving us the means to access the data stored in it, and what does this mean for us practically?
It inherits from the IDictionary class, and as such, it supports all the familiar dictionary methods like Contains
, TryGet
, and it can also be referenced by a key.
Which policies can the Context
class be used with, async or the synchronous ones?
The both.
What ability do the Context
class give us for delegate execution?
With the use of the Context
class, we can pass information directly into the delegates from the outer context. This means that we can use logic defined outside to affect delegate execution, as well as passing in details for logging or gathering metrics on our calls to remote services.
What does the use of Context
look like in terms of workflow?
The context gets populated, the request gets made and if the request fails, whether to retry is determined. If it should be retried, the context is passed into the delegate, and the delegate is executed.
During the execution of the delegate, the values that we populated inside the context can be used by the delegate as part of some decision-making logic.
What does the onRetry
delegate for a retry policy look like if we were to pass in a context to the delegate?
The third parameter of the delegate function becomes the context
.
How do you define and pass context into a policy?
By instantiating a new Context
object using a string
operation key and an IDictionary
context data object, and passing it into the ExecuteAsync
method of the policy.
var contextData = new Dictionary { ... };
var context = new Context(
“CatalogContext”, contextData);
~~~
await policy.ExecuteAsync(
context => //…
contextData)
~~~
How do you define a Retry
policy so that a context can be passed to it before execution?
By giving the RetryAsync
method’s onRetry
parameter a lambda function with three parameters. The first is for the HTTP response message, the second for the retry count, and the third for the context.
Policy .HandleResult(...) .RetryAsync( 3, onRetry: ( httpResponseMessage, retryCount, context) => {...})