generated from nventive/Template
-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathApiConfiguration.cs
More file actions
173 lines (152 loc) · 6.57 KB
/
ApiConfiguration.cs
File metadata and controls
173 lines (152 loc) · 6.57 KB
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
using System;
using System.Globalization;
using System.Net.Http;
using System.Threading.Tasks;
using ApplicationTemplate.Business;
using ApplicationTemplate.DataAccess;
using MallardMessageHandlers;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Refit;
using Uno.Extensions;
namespace ApplicationTemplate;
/// <summary>
/// This class is used for API configuration.
/// - Configures API clients.
/// - Configures HTTP handlers.
/// </summary>
public static class ApiConfiguration
{
/// <summary>
/// Adds the API services to the <see cref="IServiceCollection"/>.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection"/>.</param>
/// <param name="configuration">The <see cref="IConfiguration"/>.</param>
/// <returns>The updated <see cref="IServiceCollection"/>.</returns>
public static IServiceCollection AddApi(this IServiceCollection services, IConfiguration configuration)
{
// TODO: Configure your HTTP clients here.
// For example purpose: the following line loads the DadJokesRepository configuration section and make IOptions<DadJokesApiClientOptions> available for DI.
services.BindOptionsToConfiguration<DadJokesApiClientOptions>(configuration);
services
.AddMainHandler()
.AddNetworkExceptionHandler()
.AddExceptionHubHandler()
.AddAuthenticationTokenHandler()
.AddTransient<HttpDebuggerHandler>()
.AddResponseContentDeserializer()
.AddAuthentication()
.AddPosts(configuration)
.AddUserProfile()
.AddDadJokes(configuration);
return services;
}
private static IServiceCollection AddUserProfile(this IServiceCollection services)
{
// This one doesn't have an actual remote API yet. It's always a mock implementation.
return services.AddSingleton<IUserProfileRepository, UserProfileRepositoryMock>();
}
private static IServiceCollection AddAuthentication(this IServiceCollection services)
{
// This one doesn't have an actual remote API yet. It's always a mock implementation.
return services.AddSingleton<IAuthenticationRepository, AuthenticationRepositoryMock>();
}
private static IServiceCollection AddPosts(this IServiceCollection services, IConfiguration configuration)
{
return services
.AddSingleton<IErrorResponseInterpreter<PostErrorResponse>>(s => new ErrorResponseInterpreter<PostErrorResponse>(
(request, response, deserializedResponse) => deserializedResponse.Error != null,
(request, response, deserializedResponse) => new PostRepositoryException(deserializedResponse)
))
.AddTransient<ExceptionInterpreterHandler<PostErrorResponse>>()
.AddApiClient<IPostsRepository, PostsRepositoryMock>(configuration, "PostApiClient", b => b
.AddHttpMessageHandler<ExceptionInterpreterHandler<PostErrorResponse>>()
.AddHttpMessageHandler<AuthenticationTokenHandler<AuthenticationData>>()
);
}
private static IServiceCollection AddDadJokes(this IServiceCollection services, IConfiguration configuration)
{
return services.AddApiClient<IDadJokesRepository, DadJokesRepositoryMock>(configuration, "DadJokesApiClient");
}
private static IServiceCollection AddApiClient<TInterface, TMock>(
this IServiceCollection services,
IConfiguration configuration,
string name,
Func<IHttpClientBuilder, IHttpClientBuilder> configure = null
)
where TInterface : class
where TMock : class, TInterface
{
var mockOptions = configuration.GetSection("Mock").Get<MockOptions>();
if (mockOptions.IsMockEnabled)
{
services.AddSingleton<TInterface, TMock>();
}
else
{
var options = configuration.GetSection(name).Get<ApiClientOptions>();
var diagnosticsOptions = configuration.ReadOptions<DiagnosticsOptions>();
var httpClientBuilder = services
.AddRefitHttpClient<TInterface>()
.ConfigurePrimaryHttpMessageHandler(serviceProvider => serviceProvider.GetRequiredService<HttpMessageHandler>())
.ConfigureHttpClient((serviceProvider, client) =>
{
client.BaseAddress = options.Url;
AddDefaultHeaders(client, serviceProvider);
})
.AddConditionalHttpMessageHandler<HttpDebuggerHandler>(diagnosticsOptions.IsHttpDebuggerEnabled)
.AddHttpMessageHandler<ExceptionHubHandler>();
configure?.Invoke(httpClientBuilder);
httpClientBuilder.AddHttpMessageHandler<NetworkExceptionHandler>();
}
return services;
}
private static IServiceCollection AddMainHandler(this IServiceCollection services)
{
return services.AddTransient<HttpMessageHandler, HttpClientHandler>();
}
private static IServiceCollection AddResponseContentDeserializer(this IServiceCollection services)
{
return services.AddSingleton<IResponseContentDeserializer, JsonSerializerToResponseContentSererializerAdapter>();
}
private static IServiceCollection AddNetworkExceptionHandler(this IServiceCollection services)
{
return services
.AddSingleton<INetworkAvailabilityChecker>(s =>
new NetworkAvailabilityChecker(ct => Task.FromResult(s.GetRequiredService<IConnectivityProvider>().NetworkAccess is NetworkAccess.Internet))
)
.AddTransient<NetworkExceptionHandler>();
}
private static IServiceCollection AddExceptionHubHandler(this IServiceCollection services)
{
return services
.AddSingleton<IExceptionHub>(new ExceptionHub())
.AddTransient<ExceptionHubHandler>();
}
private static IServiceCollection AddAuthenticationTokenHandler(this IServiceCollection services)
{
return services
.AddSingleton<IAuthenticationTokenProvider<AuthenticationData>>(s => s.GetRequiredService<IAuthenticationService>())
.AddTransient<AuthenticationTokenHandler<AuthenticationData>>();
}
private static void AddDefaultHeaders(HttpClient client, IServiceProvider serviceProvider)
{
client.DefaultRequestHeaders.Add("Accept-Language", CultureInfo.CurrentCulture.Name);
client.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", "DadJokesApp/1.0.0");
}
/// <summary>
/// Adds a Refit client to the service collection.
/// </summary>
/// <typeparam name="T">The type of the Refit interface.</typeparam>
/// <param name="services">The service collection.</param>
/// <param name="settings">Optional. The settings to configure the instance with.</param>
/// <returns>The updated IHttpClientBuilder.</returns>
private static IHttpClientBuilder AddRefitHttpClient<T>(this IServiceCollection services, Func<IServiceProvider, RefitSettings> settings = null)
where T : class
{
services.AddSingleton(serviceProvider => RequestBuilder.ForType<T>(settings?.Invoke(serviceProvider)));
return services
.AddHttpClient(typeof(T).FullName)
.AddTypedClient((client, serviceProvider) => RestService.For(client, serviceProvider.GetService<IRequestBuilder<T>>()));
}
}