Skip to content
reisenberger edited this page Jun 24, 2017 · 14 revisions

PolicyRegistry

Purpose

PolicyRegistry provides a registry for storing configured policy instances and retrieving them later for use.

PolicyRegistry promotes separation of policy definition and usage, enabling common patterns such as defining policies centrally on start-up, and passing them to point-of-use by dependency injection.

A PolicyRegistry instance may typically be accessed around the app by dependency injection or the ambient-context pattern.

Syntax

PolicyRegistry has Dictionary<string, Policy>-like semantics.

Create a registry

PolicyRegistry registry = new PolicyRegistry();

Populate a registry with policies

registry.Add("StandardHttpResilience", myStandardHttpResiliencePolicy);
// Or:
registry["StandardHttpResilience"] = myStandardHttpResiliencePolicy;

Provide the registry to usage sites

// Pass the registry instance to usage sites by DI, perhaps
public class MyServiceGateway 
{
    public void MyServiceGateway(..., IPolicyRegistry<string> registry, ...)
    {
       ...
    } 
}

For those who prefer, a PolicyRegistry instance could be exposed as a thread-safe singleton, allowing it to be used as an ambient context.

Use policies from the registry

registry.Get<IAsyncPolicy<HttpResponseMessage>>("StandardHttpResilience")
    .ExecuteAsync<HttpResponseMessage>(...)

Further syntax

PolicyRegistry exposes further semantics, with standard dictionary-like behaviour:

  • .ContainsKey(...)
  • .TryGet<TPolicy>(...)
  • .Count
  • .Clear()
  • Remove(...).

Operation

The default implementation is in-memory, backed by ConcurrentDictionary.

What does the key represent?

The default implementation is (intentionally) agnostic about what the string key represents, for maximum flexibility. Users may define their own patterns for keys.

Extending Polly's registry with IPolicyRegistry<in TKey>

Polly also exposes an IPolicyRegistry<in TKey> interface. You may fulfil this interface with your own implementation. This could be used, for example:

  • to provide an implementation backed by an alternative store
  • to provide an implementation with a compound TKey of some kind.
Clone this wiki locally