简体   繁体   中英

How to use Polly and IHttpClientFactory per url

I am trying to find a way to use a HttpClient using IHttpClientFactory.CreateClient([name]) where [name] is an HttpClient that was configured using Polly in the Startup class using PolicyRegistry . I want that policy to apply for each of the urls that i make calls using that client.

So if I create a client called "myclient" and throughout my application I will make calls to N different urls, using that named client, I want to have the policy applied for each url individually, not as a whole.

Startup

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

Some Consumer Service

public class SomeService
{
    private IHttpClientFactory factory;
    public SomeService(IHttpClientFactory factory)
    {
        this.factory=factory;
    }
    public void SomeCall(string url)
    {
        var client=factory.GetClient("someClient");
        client.SendAsync(...);
    }
}

In the above case I want the policy set up in the startup class to be taken individually for each of the urls that I am calling.

Is that possible?

In order to achieve that you need to register your HttpClient and your PolicyRegistry separately:

services.AddHttpClient("someClient");
services.AddPolicyRegistry(registry);

Then you can ask the DI to provide that registry for you:

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;
    }
    ...
}

Finally inside your SomeCall you can retrieve the policy:

public async Task SomeCall(string url)
{
     var client = factory.GetClient("someClient");
     var policy = policyRegistry.Get<IAsyncPolicy>("type1");

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM