Created
April 26, 2020 05:04
-
-
Save finesse-fingers/3976a78f1528809bbbb1f77f46a63c16 to your computer and use it in GitHub Desktop.
Typed http client configuration and registration
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class ServiceExtensions | |
{ | |
public static IServiceCollection AddTypedHttpClient(this IServiceCollection service, IConfiguration configuration) | |
{ | |
service.Configure<HttpClientConfiguration>( | |
configuration.GetSection(nameof(HttpClientConfiguration))); | |
var provider = service.BuildServiceProvider(); | |
var httpConfiguration = provider.GetService<IOptions<HttpClientConfiguration>>().Value; | |
service.AddHttpClient<IMyHttpClient, MyHttpClient>(c => | |
{ | |
if (!string.IsNullOrEmpty(httpConfiguration.BaseAddress)) | |
{ | |
c.BaseAddress = new Uri(httpConfiguration.BaseAddress); | |
} | |
if (!string.IsNullOrEmpty(httpConfiguration.XApiKey)) | |
{ | |
c.DefaultRequestHeaders.TryAddWithoutValidation("X-Api-Key", httpConfiguration.XApiKey); | |
} | |
// add any other headers | |
foreach (var header in httpConfiguration.DefaultHeaders) | |
{ | |
c.DefaultRequestHeaders.TryAddWithoutValidation(header.Key, header.Value); | |
} | |
c.Timeout = httpConfiguration.RequestTimeout; | |
}) | |
.AddTransientHttpErrorPolicy(httpConfiguration.RetryCount, httpConfiguration.RetryWaitDuration); | |
return service; | |
} | |
public static IHttpClientBuilder AddTransientHttpErrorPolicy( | |
this IHttpClientBuilder builder, int retryCount, TimeSpan duration) | |
{ | |
builder.AddTransientHttpErrorPolicy(p => p.WaitAndRetryAsync(retryCount, _ => duration)); | |
return builder; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class HttpClientConfiguration | |
{ | |
public string HttpClientName { get; set; } = "DefaultHttpClient"; | |
public string BaseAddress { get; set; } | |
public string RequestUri { get; set; } | |
public List<HttpHeaderParameters> DefaultHeaders { get; set; } = new List<HttpHeaderParameters>(); | |
public string XApiKey { get; set; } | |
public int RetryCount { get; set; } = 3; | |
public TimeSpan RetryWaitDuration { get; set; } = TimeSpan.FromMilliseconds(600); | |
public TimeSpan RequestTimeout { get; set; } = TimeSpan.FromHours(1); | |
} | |
public class HttpHeaderParameters | |
{ | |
public string Key { get; set; } | |
public string Value { get; set; } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment