Skip to content

Commit 364c2f4

Browse files
Update httpclient-guidelines.md (#36866)
* Update httpclient-guidelines.md Added example of using a Polly policy with a static HttpClient instance. * Update docs/fundamentals/networking/http/httpclient-guidelines.md Co-authored-by: David Pine <[email protected]> * Update docs/fundamentals/networking/http/httpclient-guidelines.md Co-authored-by: David Pine <[email protected]> * Apply suggestions from code review --------- Co-authored-by: David Pine <[email protected]>
1 parent 7696acd commit 364c2f4

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

docs/fundamentals/networking/http/httpclient-guidelines.md

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,38 @@ To summarize recommended `HttpClient` use in terms of lifetime management, you s
5252
5353
For more information about managing `HttpClient` lifetime with `IHttpClientFactory`, see [`IHttpClientFactory` guidelines](../../../core/extensions/httpclient-factory.md#httpclient-lifetime-management).
5454

55+
## Resilience policies with static clients
56+
57+
It's possible to configure a `static` or *singleton* client to use any number of resilience policies using the following pattern:
58+
59+
```csharp
60+
using System;
61+
using System.Net.Http;
62+
using Microsoft.Extensions.Http;
63+
using Polly;
64+
using Polly.Extensions.Http;
65+
66+
var retryPolicy = HttpPolicyExtensions
67+
.HandleTransientHttpError()
68+
.WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)));
69+
70+
var socketHandler = new SocketsHttpHandler { PooledConnectionLifetime = TimeSpan.FromMinutes(15) };
71+
var pollyHandler = new PolicyHttpMessageHandler(retryPolicy)
72+
{
73+
InnerHandler = socketHandler;
74+
};
75+
76+
var httpClient = new HttpClient(pollyHandler);
77+
```
78+
79+
The preceding code:
80+
81+
- Relies on [Microsoft.Extensions.Http.Polly](https://www.nuget.org/packages/Microsoft.Extensions.Http.Polly) NuGet package, transitively the [Polly.Extensions.Http](https://www.nuget.org/packages/Polly.Extensions.Http) NuGet package for the `HttpPolicyExtensions` type.
82+
- Specifies a transient HTTP error handler, configured with retry policy that with each attempt will exponentially backoff delay intervals.
83+
- Defines a pooled connection lifetime of fifteen minutes for the `socketHandler`.
84+
- Passes the `socketHandler` to the `policyHandler` with the retry logic.
85+
- Instantiates an `HttpClient` given the `policyHandler`.
86+
5587
## See also
5688

5789
- [HTTP support in .NET](http-overview.md)

0 commit comments

Comments
 (0)