-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathServiceCollectionsExtensions.cs
More file actions
316 lines (284 loc) · 12.5 KB
/
ServiceCollectionsExtensions.cs
File metadata and controls
316 lines (284 loc) · 12.5 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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
using System;
// ReSharper disable once RedundantUsingDirective
// Note: Necessary for .NET 4.7.2/4.8.2
using System.Linq;
using System.Net.Http.Headers;
using System.Reflection;
using System.Runtime.InteropServices;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using Mindee.Http;
using Mindee.Pdf;
using RestSharp;
namespace Mindee.Extensions.DependencyInjection
{
#if !NET6_0_OR_GREATER
/// <summary>
/// Wrapper for V2 RestClient to work around lack of keyed services in .NET Framework
/// </summary>
internal sealed class MindeeV2RestClientWrapper
{
public RestClient Client { get; }
public MindeeV2RestClientWrapper(RestClient client)
{
Client = client;
}
}
#endif
/// <summary>
/// To configure DI.
/// </summary>
public static class ServiceCollectionsExtensions
{
/// <summary>
/// Configure the Mindee API in the DI, mainly used for mocking/testing purposes.
/// </summary>
/// <param name="services"></param>
/// <param name="configureOptions"></param>
/// <param name="throwOnError"></param>
/// <returns></returns>
public static void AddMindeeApi(
this IServiceCollection services,
Action<MindeeSettings> configureOptions,
bool throwOnError = false)
{
services.Configure(configureOptions);
RegisterV1RestSharpClient(services, throwOnError);
services.AddSingleton(serviceProvider =>
{
var settings = serviceProvider.GetRequiredService<IOptions<MindeeSettings>>();
var restClient = serviceProvider.GetRequiredService<RestClient>();
var logger = serviceProvider.GetService<ILoggerFactory>()?.CreateLogger<MindeeApi>();
return new MindeeApi(settings, restClient, logger);
});
}
/// <summary>
/// Configure the Mindee API in the DI, mainly used for mocking/testing purposes.
/// </summary>
/// <param name="services"></param>
/// <param name="configureOptions"></param>
/// <param name="loggerFactory"></param>
/// <param name="throwOnError"></param>
/// <returns></returns>
public static void AddMindeeApiV2(
this IServiceCollection services,
Action<MindeeSettingsV2> configureOptions,
ILoggerFactory loggerFactory = null,
bool throwOnError = false)
{
services.Configure(configureOptions);
RegisterV2RestSharpClient(services, throwOnError);
if (loggerFactory is not null)
{
services.AddSingleton(loggerFactory);
}
else if (services.All(d => d.ServiceType != typeof(ILoggerFactory)))
{
services.AddSingleton<ILoggerFactory, NullLoggerFactory>();
services.AddSingleton(typeof(ILogger<>), typeof(NullLogger<>));
}
services.AddSingleton(serviceProvider =>
{
var settings = serviceProvider.GetRequiredService<IOptions<MindeeSettingsV2>>();
#if NET6_0_OR_GREATER
var restClient = serviceProvider.GetRequiredKeyedService<RestClient>("MindeeV2RestClient");
#else
var restClient = serviceProvider.GetRequiredService<MindeeV2RestClientWrapper>().Client;
#endif
var logger = serviceProvider.GetService<ILoggerFactory>()?.CreateLogger<MindeeApiV2>();
return new MindeeApiV2(settings, restClient, logger);
});
}
private static void RegisterV1RestSharpClient(IServiceCollection services, bool throwOnError)
{
services.AddSingleton(provider =>
{
var settings = provider.GetRequiredService<IOptions<MindeeSettings>>().Value;
settings.MindeeBaseUrl = Environment.GetEnvironmentVariable("Mindee__BaseUrl");
if (string.IsNullOrEmpty(settings.MindeeBaseUrl))
{
settings.MindeeBaseUrl = "https://api.mindee.net";
}
if (settings.RequestTimeoutSeconds <= 0)
{
settings.RequestTimeoutSeconds = 120;
}
if (string.IsNullOrEmpty(settings.ApiKey))
{
settings.ApiKey = Environment.GetEnvironmentVariable("Mindee__ApiKey");
}
var clientOptions = new RestClientOptions(settings.MindeeBaseUrl)
{
FollowRedirects = false,
Timeout = TimeSpan.FromSeconds(settings.RequestTimeoutSeconds),
UserAgent = BuildUserAgent(),
Expect100Continue = false,
CachePolicy = new CacheControlHeaderValue { NoCache = true, NoStore = true },
ThrowOnAnyError = throwOnError
};
return new RestClient(clientOptions);
});
}
private static void RegisterV2RestSharpClient(IServiceCollection services, bool throwOnError)
{
#if NET6_0_OR_GREATER
services.AddKeyedSingleton("MindeeV2RestClient", (provider, _) =>
{
var settings = provider.GetRequiredService<IOptions<MindeeSettingsV2>>().Value;
settings.MindeeBaseUrl = Environment.GetEnvironmentVariable("MindeeV2__BaseUrl");
if (string.IsNullOrEmpty(settings.MindeeBaseUrl))
{
settings.MindeeBaseUrl = "https://api-v2.mindee.net";
}
if (settings.RequestTimeoutSeconds <= 0)
{
settings.RequestTimeoutSeconds = 120;
}
if (string.IsNullOrEmpty(settings.ApiKey))
{
settings.ApiKey = Environment.GetEnvironmentVariable("MindeeV2__ApiKey");
}
var clientOptions = new RestClientOptions(settings.MindeeBaseUrl)
{
FollowRedirects = false,
Timeout = TimeSpan.FromSeconds(settings.RequestTimeoutSeconds),
UserAgent = BuildUserAgent(),
Expect100Continue = false,
CachePolicy = new CacheControlHeaderValue { NoCache = true, NoStore = true },
ThrowOnAnyError = throwOnError
};
return new RestClient(clientOptions);
});
#else
// For .NET Framework, register as a named singleton using a wrapper approach
services.AddSingleton(provider =>
{
var settings = provider.GetRequiredService<IOptions<MindeeSettingsV2>>().Value;
settings.MindeeBaseUrl = Environment.GetEnvironmentVariable("MindeeV2__BaseUrl");
if (string.IsNullOrEmpty(settings.MindeeBaseUrl))
{
settings.MindeeBaseUrl = "https://api-v2.mindee.net";
}
if (settings.RequestTimeoutSeconds <= 0)
{
settings.RequestTimeoutSeconds = 120;
}
if (string.IsNullOrEmpty(settings.ApiKey))
{
settings.ApiKey = Environment.GetEnvironmentVariable("MindeeV2__ApiKey");
}
var clientOptions = new RestClientOptions
{
BaseUrl = new Uri(settings.MindeeBaseUrl),
FollowRedirects = false,
Timeout = TimeSpan.FromSeconds(settings.RequestTimeoutSeconds),
UserAgent = BuildUserAgent(),
Expect100Continue = false,
CachePolicy = new CacheControlHeaderValue { NoCache = true, NoStore = true },
ThrowOnAnyError = throwOnError
};
return new MindeeV2RestClientWrapper(new RestClient(clientOptions));
});
#endif
}
private static string BuildUserAgent()
{
string platform;
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
platform = "windows";
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
platform = "linux";
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
platform = "macos";
}
else
{
platform = "other";
}
return $"mindee-api-dotnet@v{Assembly.GetExecutingAssembly().GetName().Version}"
+ $" dotnet-v{Environment.Version}"
+ $" {platform}";
}
/// <summary>
/// Configure the Mindee client in the DI.
/// </summary>
/// <param name="services">
/// <c>IServiceCollection</c>
/// </param>
/// <param name="sectionName">The name of the section to bind from the configuration.</param>
/// <remarks>The <see cref="MindeeClient" /> instance is registered as a transient.</remarks>
public static IServiceCollection AddMindeeClient(
this IServiceCollection services,
string sectionName = "Mindee")
{
services.AddSingleton<MindeeClient>();
services.AddSingleton<IHttpApi, MindeeApi>();
services.AddOptions<MindeeSettings>()
.BindConfiguration(sectionName)
.Validate(settings => !string.IsNullOrEmpty(settings.ApiKey), "The Mindee V1 API key is missing");
RegisterV1RestSharpClient(services, false);
services.AddPdfOperation();
return services;
}
/// <summary>
/// Configure the Mindee client V2 in the DI.
/// </summary>
/// <param name="services">
/// <c>IServiceCollection</c>
/// </param>
/// <param name="sectionName">The name of the section to bind from the configuration.</param>
/// <remarks>The <see cref="MindeeClient" /> instance is registered as a transient.</remarks>
public static IServiceCollection AddMindeeClientV2(
this IServiceCollection services,
string sectionName = "MindeeV2")
{
services.AddSingleton<MindeeClientV2>();
services.AddSingleton<HttpApiV2, MindeeApiV2>();
services.AddOptions<MindeeSettingsV2>()
.BindConfiguration(sectionName)
.Validate(settings => !string.IsNullOrEmpty(settings.ApiKey), "The Mindee V2 API key is missing");
RegisterV2RestSharpClient(services, false);
services.AddPdfOperation();
return services;
}
/// <summary>
/// Configure the Mindee client in the DI with your own custom pdf implementation.
/// </summary>
/// <typeparam name="TPdfOperationImplementation">Will be registered as a singleton.</typeparam>
/// <remarks>The <see cref="MindeeClient" /> instance is registered as a transient.</remarks>
public static IServiceCollection AddMindeeClientWithCustomPdfImplementation<TPdfOperationImplementation>(
this IServiceCollection services)
where TPdfOperationImplementation : class, IPdfOperation, new()
{
services.AddSingleton<MindeeClient>();
services.AddSingleton<IPdfOperation, TPdfOperationImplementation>();
return services;
}
/// <summary>
/// Configure the Mindee client V2 in the DI with your own custom pdf implementation.
/// </summary>
/// <typeparam name="TPdfOperationImplementation">Will be registered as a singleton.</typeparam>
/// <remarks>The <see cref="MindeeClient" /> instance is registered as a transient.</remarks>
public static IServiceCollection AddMindeeClientV2WithCustomPdfImplementation<TPdfOperationImplementation>(
this IServiceCollection services)
where TPdfOperationImplementation : class, IPdfOperation, new()
{
services.AddSingleton<MindeeClientV2>();
services.AddSingleton<IPdfOperation, TPdfOperationImplementation>();
return services;
}
internal static IServiceCollection AddPdfOperation(
this IServiceCollection services)
{
services.AddSingleton<IPdfOperation, DocNetApi>();
return services;
}
}
}