Polly icon indicating copy to clipboard operation
Polly copied to clipboard

Create policy at runtime based on url

Open sanzor opened this issue 2 years ago • 0 comments

I am using Polly with IHttpClientFactory in a ASP Net Core application and i am trying to create a IAsyncPolicy object instance for each unique url that my service is calling:

Startup

PolicyRegistry registry = new PolicyRegistry();
AsyncPolicyWrap type1Policy = //somePolicy;
registry.Add("type1",type1Policy);
services.AddHttpClient("someClient").AddPolicyHandlerFromRegistry("type1");

Service

public class SomeService
{
    private readonly IHttpClientFactory factory;
    private readonly IReadOnlyPolicyRegistry<string> policyRegistry;

    public SomeService(IHttpClientFactory factory, IReadOnlyPolicyRegistry<string> policyRegistry)
    {
        this.factory = factory;
        this.policyRegistry = policyRegistry;
    }
    public async Task SomeCall(string url)
{
     var client = factory.GetClient("someClient");
     var policy = policyRegistry.Get<IAsyncPolicy>("type1"); //create a new policy of type1 but for this specific url !!!

     await policy.ExecuteAsync(async ct => await client.SendAsync(..., ct), CancellationToken.None);
}
}

In the code above, i want somehow to create a new policy of type type1 for each unique url. So therefore i need some sort of caching to be done each time a new url is specified.

Summary ! In the code above in the SomeService class the problem is that i do not want a one policy instance of type type1 for all my urls. If url1 produces a retry i do not want it be aggregated in the same place where url2 or urlN produce failures.

Do i need to produce a caching layer and store something like a thread-safe Dictionary<string,IAsyncPolicy> (url and policy) or can polly handle that ?

Original quesiton can be found on Stackoverflow

sanzor avatar Dec 15 '21 19:12 sanzor