-
Notifications
You must be signed in to change notification settings - Fork 0
/
ServiceCollectionExtensions.cs
40 lines (33 loc) · 1.49 KB
/
ServiceCollectionExtensions.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
using Microsoft.Extensions.Configuration;
using OnCourse.Kami.Configuration;
using Polly;
using OnCourse.Kami;
using Ardalis.GuardClauses;
namespace Microsoft.Extensions.DependencyInjection;
public static class ServiceCollectionExtensions
{
public static IServiceCollection AddKamiClient(this IServiceCollection services, IConfiguration configuration)
{
return services.AddKamiClient(configuration, null);
}
public static IServiceCollection AddKamiClient(this IServiceCollection services, IConfiguration configuration, Func<PolicyBuilder<HttpResponseMessage>, IAsyncPolicy<HttpResponseMessage>>? errorPolicy = null)
{
services.Configure<KamiOptions>(configuration.GetSection(KamiOptions.SectionName));
var address = configuration["Kami:BaseAddress"];
var token = configuration["Kami:Token"];
Guard.Against.NullOrEmpty(address, "Kami:BassAddress", "Missing Kami BaseAddress in settings.");
Guard.Against.NullOrEmpty(token, "Kami:Token", "Missing Kami Token in settings.");
services.AddHttpClient<IKamiClient, KamiClient>(client =>
{
client.BaseAddress = new Uri(address);
client.DefaultRequestHeaders.TryAddWithoutValidation("authorization", token);
})
.AddTransientHttpErrorPolicy(errorPolicy ?? (p => p.WaitAndRetryAsync(new[]
{
TimeSpan.FromSeconds(1),
TimeSpan.FromSeconds(5),
TimeSpan.FromSeconds(10)
})));
return services;
}
}