Repository navigation
Expand file tree
/
Copy pathServiceCollectionExtensions.cs
More file actions
583 lines (525 loc) · 27 KB
/
Copy pathServiceCollectionExtensions.cs
File metadata and controls
583 lines (525 loc) · 27 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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
// -----------------------------------------------------------------------
// 作者:Mud Studio 版权所有 (c) Mud Studio 2026
// Mud.HttpUtils 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
// 本项目主要遵循 MIT 许可证进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 文件。
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动!任何基于本项目开发而产生的一切法律纠纷和责任,我们不承担任何责任!
// -----------------------------------------------------------------------
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
#if NET6_0_OR_GREATER
using System.Diagnostics.CodeAnalysis;
#endif
namespace Mud.HttpUtils.Resilience;
/// <summary>
/// 提供 Microsoft.Extensions.DependencyInjection 的扩展方法,用于注册 Mud.HttpUtils 弹性策略服务。
/// </summary>
/// <remarks>
/// 本类提供以下核心功能:
/// <list type="bullet">
/// <item><description>注册弹性策略提供器(<see cref="IResiliencePolicyProvider"/>)</description></item>
/// <item><description>为 <see cref="IEnhancedHttpClient"/> 添加弹性策略装饰器</description></item>
/// <item><description>一站式注册方法(<c>AddMudHttpUtils</c>)同时配置 HttpClient 和弹性策略</description></item>
/// </list>
/// </remarks>
public static class ServiceCollectionExtensions
{
/// <summary>
/// 注册 Mud.HttpUtils 弹性策略服务,使用委托配置弹性策略选项。
/// </summary>
/// <param name="services">服务集合。</param>
/// <param name="configureOptions">用于配置 <see cref="ResilienceOptions"/> 的委托(可选)。</param>
/// <returns>服务集合(链式调用)。</returns>
/// <exception cref="ArgumentNullException"><paramref name="services"/> 为 null 时抛出。</exception>
/// <example>
/// <code>
/// services.AddMudHttpResilience(options =>
/// {
/// options.Retry.MaxRetryAttempts = 3;
/// options.Timeout.TimeoutSeconds = 30;
/// });
/// </code>
/// </example>
public static IServiceCollection AddMudHttpResilience(
this IServiceCollection services,
Action<ResilienceOptions>? configureOptions = null)
{
if (services == null)
throw new ArgumentNullException(nameof(services));
services.AddOptions<ResilienceOptions>();
if (configureOptions != null)
{
services.Configure(configureOptions);
}
services.TryAddSingleton<IValidateOptions<ResilienceOptions>, ResilienceOptionsValidator>();
// 注册跨选项后置配置器,检查 HttpClient.Timeout 与 Polly 重试/超时的潜在冲突
services.TryAddSingleton<IPostConfigureOptions<ResilienceOptions>, ResilienceOptionsCrossValidator>();
// AllowNonIdempotentRetry=true 且方法集合被收窄时告警(RetryableHttpMethods 将被忽略)
services.TryAddSingleton<IPostConfigureOptions<ResilienceOptions>, ResilienceOptionsPostConfigure>();
services.TryAddSingleton<IResiliencePolicyProvider>(CreatePolicyProvider);
// 注册弹性策略解析器,供 IHttpRequestExecutor 在运行时编排方法级弹性策略
services.TryAddSingleton<IResiliencePolicyResolver, ResiliencePolicyResolver>();
return services;
}
/// <summary>
/// 注册 per-app 弹性策略解析器(按应用隔离重试/超时/熔断)。
/// </summary>
/// <param name="services">服务集合。</param>
/// <param name="perAppOptionsFactory">按 appKey 获取专属弹性选项的工厂;返回 null 表示该应用无专属策略(回退全局)。</param>
/// <param name="configureDefaultOptions">全局(默认)弹性选项配置委托(可选)。</param>
/// <param name="maxCachedApps">per-app 缓存上限,默认 1024。</param>
/// <returns>服务集合(链式调用)。</returns>
/// <remarks>
/// <para>
/// 内部同时确保 <see cref="IResiliencePolicyResolver"/> 已注册(<c>TryAddSingleton</c>),
/// 并订阅 <c>IOptionsMonitor<ResilienceOptions></c> 变更:配置热更新会清空 per-app 缓存,
/// 使新配置在下一次请求生效。
/// </para>
/// <para>
/// 若同时注册了 <see cref="IAppContextHolder"/>(由 <c>AddMudHttpAppContextHolder()</c> 或配置入口自动补齐),
/// <c>DefaultHttpRequestExecutor</c> 即会按当前 AppKey 路由到该应用的专属策略。
/// </para>
/// </remarks>
public static IServiceCollection AddMudHttpAppResilience(
this IServiceCollection services,
Func<string, ResilienceOptions?> perAppOptionsFactory,
Action<ResilienceOptions>? configureDefaultOptions = null,
int maxCachedApps = 1024)
{
if (services == null)
throw new ArgumentNullException(nameof(services));
if (perAppOptionsFactory == null)
throw new ArgumentNullException(nameof(perAppOptionsFactory));
services.AddMudHttpResilience(configureDefaultOptions);
services.TryAddSingleton<IAppResiliencePolicyResolver>(sp =>
{
var resolver = new AppResiliencePolicyResolver(
perAppOptionsFactory,
sp.GetService<ILogger<AppResiliencePolicyResolver>>(),
maxCachedApps);
// IOptionsMonitor 在未注册 Options 的老容器中可能为 null,需容错
if (sp.GetService<IOptionsMonitor<ResilienceOptions>>() is { } monitor)
resolver.SubscribeToOptionChanges(monitor);
return resolver;
});
return services;
}
/// <param name="services">服务集合。</param>
/// <param name="configuration">配置实例,用于绑定弹性策略选项。</param>
/// <param name="configurationSectionPath">配置文件中弹性策略节点的路径,默认为 <see cref="ResilienceOptions.SectionName"/>。</param>
/// <returns>服务集合(链式调用)。</returns>
/// <exception cref="ArgumentNullException"><paramref name="services"/> 或 <paramref name="configuration"/> 为 null 时抛出。</exception>
/// <example>
/// 在 appsettings.json 中配置:
/// <code>
/// {
/// "MudHttpResilience": {
/// "Retry": {
/// "MaxRetryAttempts": 3,
/// "DelayMilliseconds": 1000
/// },
/// "Timeout": {
/// "TimeoutSeconds": 30
/// }
/// }
/// }
/// </code>
/// 然后在代码中:
/// <code>
/// services.AddMudHttpResilience(Configuration);
/// </code>
/// </example>
#if NET6_0_OR_GREATER
[System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessage("Microsoft.Extensions.Configuration.ConfigurationBinder", "IL2026:RequiresUnreferencedCode",
Justification = "配置绑定路径在 AOT 下需通过委托式重载 AddMudHttpResilience(Action<ResilienceOptions>) 替代。")]
[System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessage("AotAnalysis", "IL3050:RequiresDynamicCode",
Justification = "配置绑定路径在 AOT 下需通过委托式重载替代。")]
#endif
public static IServiceCollection AddMudHttpResilience(
this IServiceCollection services,
IConfiguration configuration,
string configurationSectionPath = ResilienceOptions.SectionName)
{
if (services == null)
throw new ArgumentNullException(nameof(services));
if (configuration == null)
throw new ArgumentNullException(nameof(configuration));
// 使用 IConfiguration 直接绑定,支持 IOptionsMonitor 变更通知。
// 注意:PollyResiliencePolicyProvider 注册为单例并通过 IOptions<ResilienceOptions> 读取配置,
// 因此策略在启动时创建一次,不会随配置热更新而动态变化。
services.Configure<ResilienceOptions>(configuration.GetSection(configurationSectionPath));
services.TryAddSingleton<IValidateOptions<ResilienceOptions>, ResilienceOptionsValidator>();
// 注册跨选项后置配置器,检查 HttpClient.Timeout 与 Polly 重试/超时的潜在冲突
services.TryAddSingleton<IPostConfigureOptions<ResilienceOptions>, ResilienceOptionsCrossValidator>();
// AllowNonIdempotentRetry=true 且方法集合被收窄时告警(RetryableHttpMethods 将被忽略)
services.TryAddSingleton<IPostConfigureOptions<ResilienceOptions>, ResilienceOptionsPostConfigure>();
services.TryAddSingleton<IResiliencePolicyProvider>(CreatePolicyProvider);
// 注册弹性策略解析器,供 IHttpRequestExecutor 在运行时编排方法级弹性策略
services.TryAddSingleton<IResiliencePolicyResolver, ResiliencePolicyResolver>();
return services;
}
private static IEnhancedHttpClient CreateResilientDecorator(IEnhancedHttpClient inner, IServiceProvider sp)
{
var policyProvider = sp.GetRequiredService<IResiliencePolicyProvider>();
var logger = sp.GetService<ILogger<ResilientHttpClient>>();
var options = sp.GetService<IOptions<ResilienceOptions>>()?.Value;
return new ResilientHttpClient(inner, policyProvider, logger, options);
}
/// <summary>
/// 为已注册的 IEnhancedHttpClient 服务添加弹性策略装饰器。
/// </summary>
/// <remarks>
/// 此方法会装饰所有已注册的 IEnhancedHttpClient 实现,包括通过 AddMudHttpClient 注册的客户端、
/// 通过工厂创建的客户端,以及 .NET 8+ 环境下带键的服务注册。
/// 调用此方法前,必须先注册 IEnhancedHttpClient 服务。
/// </remarks>
/// <param name="services">服务集合。</param>
/// <param name="configureOptions">用于配置 ResilienceOptions 的委托(可选)。</param>
/// <returns>服务集合(链式调用)。</returns>
/// <exception cref="ArgumentNullException">services 为 null 时抛出。</exception>
/// <exception cref="InvalidOperationException">未找到已注册的 IEnhancedHttpClient 服务时抛出。</exception>
public static IServiceCollection AddMudHttpResilienceDecorator(
this IServiceCollection services,
Action<ResilienceOptions>? configureOptions = null)
{
if (services == null)
throw new ArgumentNullException(nameof(services));
services.AddMudHttpResilience(configureOptions);
DecorateFactoryEntries(services);
#if NET6_0_OR_GREATER
DecorateKeyedServices<IEnhancedHttpClient>(services, CreateResilientDecorator);
#endif
DecorateService<IEnhancedHttpClient>(services, CreateResilientDecorator);
return services;
}
/// <summary>
/// 为已注册的 IEnhancedHttpClient 服务添加弹性策略装饰器,从配置文件绑定弹性策略选项。
/// </summary>
/// <remarks>
/// 此方法会装饰所有已注册的 IEnhancedHttpClient 实现。
/// 调用此方法前,必须先注册 IEnhancedHttpClient 服务。
/// </remarks>
/// <param name="services">服务集合。</param>
/// <param name="configuration">配置实例,用于绑定弹性策略选项。</param>
/// <param name="configurationSectionPath">配置文件中弹性策略节点的路径,默认为 <see cref="ResilienceOptions.SectionName"/>。</param>
/// <returns>服务集合(链式调用)。</returns>
/// <exception cref="ArgumentNullException">services 为 null 时抛出。</exception>
/// <exception cref="InvalidOperationException">未找到已注册的 IEnhancedHttpClient 服务时抛出。</exception>
public static IServiceCollection AddMudHttpResilienceDecorator(
this IServiceCollection services,
IConfiguration configuration,
string configurationSectionPath = ResilienceOptions.SectionName)
{
if (services == null)
throw new ArgumentNullException(nameof(services));
services.AddMudHttpResilience(configuration, configurationSectionPath);
DecorateFactoryEntries(services);
#if NET8_0_OR_GREATER
DecorateKeyedServices<IEnhancedHttpClient>(services, CreateResilientDecorator);
#endif
DecorateService<IEnhancedHttpClient>(services, CreateResilientDecorator);
return services;
}
private static void DecorateFactoryEntries(IServiceCollection services)
{
services.AddSingleton<IPostConfigureOptions<EnhancedHttpClientFactoryOptions>, ResilienceDecoratorPostConfigure>();
}
#if NET6_0_OR_GREATER
private static void DecorateKeyedServices<TService>(
IServiceCollection services,
Func<TService, IServiceProvider, TService> decoratorFactory)
where TService : class
{
var keyedDescriptors = services
.Where(s => s.ServiceType == typeof(TService) && s.ServiceKey != null)
.ToList();
foreach (var descriptor in keyedDescriptors)
{
services.Remove(descriptor);
if (descriptor.KeyedImplementationFactory != null)
{
var factory = descriptor.KeyedImplementationFactory;
services.Add(new ServiceDescriptor(
typeof(TService),
descriptor.ServiceKey,
(sp, key) =>
{
var inner = (TService)factory(sp, key);
return decoratorFactory(inner, sp);
},
descriptor.Lifetime));
}
else if (descriptor.KeyedImplementationType != null)
{
var implementationType = descriptor.KeyedImplementationType;
services.Add(new ServiceDescriptor(
typeof(TService),
descriptor.ServiceKey,
(sp, key) =>
{
var inner = (TService)CreateServiceInstance(sp, implementationType!);
return decoratorFactory(inner, sp);
},
descriptor.Lifetime));
}
}
}
#endif
private static void DecorateService<TService>(
IServiceCollection services,
Func<TService, IServiceProvider, TService> decoratorFactory)
where TService : class
{
var wrappedDescriptor = services.LastOrDefault(s => s.ServiceType == typeof(TService) && s.ServiceKey == null);
if (wrappedDescriptor == null)
{
throw new InvalidOperationException(
$"未找到已注册的 {typeof(TService).Name} 服务。请先注册增强客户端(如调用 AddMudHttpClient)后再添加装饰器。");
}
services.Remove(wrappedDescriptor);
if (wrappedDescriptor.ImplementationInstance != null)
{
var instance = wrappedDescriptor.ImplementationInstance;
services.Add(new ServiceDescriptor(
typeof(TService),
sp => decoratorFactory((TService)instance, sp),
wrappedDescriptor.Lifetime));
}
else if (wrappedDescriptor.ImplementationFactory != null)
{
var factory = wrappedDescriptor.ImplementationFactory;
services.Add(new ServiceDescriptor(
typeof(TService),
sp =>
{
var inner = (TService)factory(sp);
return decoratorFactory(inner, sp);
},
wrappedDescriptor.Lifetime));
}
else if (wrappedDescriptor.ImplementationType != null)
{
var implementationType = wrappedDescriptor.ImplementationType;
services.Add(new ServiceDescriptor(
typeof(TService),
sp =>
{
var inner = (TService)CreateServiceInstance(sp, implementationType!);
return decoratorFactory(inner, sp);
},
wrappedDescriptor.Lifetime));
}
}
private static PollyResiliencePolicyProvider CreatePolicyProvider(IServiceProvider sp)
{
var options = sp.GetRequiredService<IOptions<ResilienceOptions>>();
var logger = sp.GetService<ILogger<PollyResiliencePolicyProvider>>();
return new PollyResiliencePolicyProvider(options, logger);
}
/// <summary>
/// 通过 <see cref="ActivatorUtilities.CreateInstance"/> 创建服务实例。
/// </summary>
/// <remarks>
/// <b>AOT 安全说明</b>:此方法标注了 <c>[UnconditionalSuppressMessage]</c> 以抑制 IL2026 告警。
/// 调用方(DecorateService/DecorateKeyedServices)
/// 仅在 <c>ServiceDescriptor.ImplementationType</c> 非 null 时调用此方法,而该属性的注册路径
/// (如 <c>services.AddTransient<TService, TImpl>()</c>)已通过
/// <c>[DynamicallyAccessedMembers(PublicConstructors)]</c> 保证了类型构造函数的保留。
/// AOT 场景下推荐使用工厂委托注册(<c>AddTransient<TService>(sp => ...)</c>)以完全避免此路径。
/// </remarks>
#if NET6_0_OR_GREATER
[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode",
Justification = "ImplementationType 的构造函数已由 DI 注册路径(如 AddTransient<TService,TImpl>)通过 DynamicallyAccessedMembers 保留。AOT 场景推荐使用工厂委托注册。")]
[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2067:DynamicallyAccessedMembers",
Justification = "implementationType 来源于 ServiceDescriptor.ImplementationType,该属性在 .NET 8+ 已标注 [DynamicallyAccessedMembers(PublicConstructors)],构造函数已被保留。")]
#endif
private static object CreateServiceInstance(IServiceProvider sp, Type implementationType)
{
return ActivatorUtilities.CreateInstance(sp, implementationType);
}
#region AddMudHttpUtils — 一站式注册(Client + Resilience)
/// <summary>
/// 一站式注册 Mud.HttpUtils 服务,包括 HttpClient 和弹性策略装饰器。
/// </summary>
/// <param name="services">服务集合。</param>
/// <param name="clientName">Named HttpClient 的名称。</param>
/// <param name="configureHttpClient">配置 HttpClient 的委托。</param>
/// <param name="configureResilienceOptions">配置弹性策略选项的委托(可选)。</param>
/// <returns>服务集合(链式调用)。</returns>
/// <exception cref="ArgumentNullException">参数为 null 时抛出。</exception>
public static IServiceCollection AddMudHttpUtils(
this IServiceCollection services,
string clientName,
Action<HttpClient> configureHttpClient,
Action<ResilienceOptions>? configureResilienceOptions = null)
{
if (services == null)
throw new ArgumentNullException(nameof(services));
if (string.IsNullOrWhiteSpace(clientName))
throw new ArgumentNullException(nameof(clientName));
if (configureHttpClient == null)
throw new ArgumentNullException(nameof(configureHttpClient));
services.AddMudHttpClient(clientName, configureHttpClient);
if (configureResilienceOptions != null)
{
services.AddMudHttpResilienceDecorator(configureResilienceOptions);
}
return services;
}
/// <summary>
/// 一站式注册 Mud.HttpUtils 服务,可选择是否启用弹性策略。
/// </summary>
/// <param name="services">服务集合。</param>
/// <param name="clientName">Named HttpClient 的名称。</param>
/// <param name="configureHttpClient">配置 HttpClient 的委托。</param>
/// <param name="enableResilience">是否启用弹性策略装饰器。启用后将使用默认弹性策略配置(重试3次、超时30秒)。</param>
/// <returns>服务集合(链式调用)。</returns>
/// <exception cref="ArgumentNullException">参数为 null 时抛出。</exception>
public static IServiceCollection AddMudHttpUtils(
this IServiceCollection services,
string clientName,
Action<HttpClient> configureHttpClient,
bool enableResilience)
{
if (services == null)
throw new ArgumentNullException(nameof(services));
if (string.IsNullOrWhiteSpace(clientName))
throw new ArgumentNullException(nameof(clientName));
if (configureHttpClient == null)
throw new ArgumentNullException(nameof(configureHttpClient));
services.AddMudHttpClient(clientName, configureHttpClient);
if (enableResilience)
{
services.AddMudHttpResilienceDecorator();
}
return services;
}
/// <summary>
/// 一站式注册 Mud.HttpUtils 服务,使用基础地址配置 HttpClient。
/// </summary>
/// <param name="services">服务集合。</param>
/// <param name="clientName">Named HttpClient 的名称。</param>
/// <param name="baseAddress">HttpClient 的基础地址。</param>
/// <param name="configureResilienceOptions">配置弹性策略选项的委托(可选)。</param>
/// <returns>服务集合(链式调用)。</returns>
/// <exception cref="ArgumentNullException">参数为 null 时抛出。</exception>
public static IServiceCollection AddMudHttpUtils(
this IServiceCollection services,
string clientName,
string baseAddress,
Action<ResilienceOptions>? configureResilienceOptions = null)
{
if (services == null)
throw new ArgumentNullException(nameof(services));
if (string.IsNullOrWhiteSpace(clientName))
throw new ArgumentNullException(nameof(clientName));
if (string.IsNullOrWhiteSpace(baseAddress))
throw new ArgumentNullException(nameof(baseAddress));
return services.AddMudHttpUtils(
clientName,
client => client.BaseAddress = new Uri(baseAddress),
configureResilienceOptions);
}
/// <summary>
/// 一站式注册 Mud.HttpUtils 服务,使用基础地址配置 HttpClient,可选择是否启用弹性策略。
/// </summary>
/// <param name="services">服务集合。</param>
/// <param name="clientName">Named HttpClient 的名称。</param>
/// <param name="baseAddress">HttpClient 的基础地址。</param>
/// <param name="enableResilience">是否启用弹性策略装饰器。启用后将使用默认弹性策略配置(重试3次、超时30秒)。</param>
/// <returns>服务集合(链式调用)。</returns>
/// <exception cref="ArgumentNullException">参数为 null 时抛出。</exception>
public static IServiceCollection AddMudHttpUtils(
this IServiceCollection services,
string clientName,
string baseAddress,
bool enableResilience)
{
if (services == null)
throw new ArgumentNullException(nameof(services));
if (string.IsNullOrWhiteSpace(clientName))
throw new ArgumentNullException(nameof(clientName));
if (string.IsNullOrWhiteSpace(baseAddress))
throw new ArgumentNullException(nameof(baseAddress));
return services.AddMudHttpUtils(
clientName,
client => client.BaseAddress = new Uri(baseAddress),
enableResilience);
}
/// <summary>
/// 一站式注册 Mud.HttpUtils 服务,从配置文件绑定弹性策略选项。
/// </summary>
/// <param name="services">服务集合。</param>
/// <param name="clientName">Named HttpClient 的名称。</param>
/// <param name="configuration">配置实例。</param>
/// <param name="configureHttpClient">配置 HttpClient 的委托。</param>
/// <param name="resilienceSectionPath">弹性策略配置节点路径,默认 <see cref="ResilienceOptions.SectionName"/>。</param>
/// <returns>服务集合(链式调用)。</returns>
/// <exception cref="ArgumentNullException">参数为 null 时抛出。</exception>
public static IServiceCollection AddMudHttpUtils(
this IServiceCollection services,
string clientName,
IConfiguration configuration,
Action<HttpClient> configureHttpClient,
string resilienceSectionPath = ResilienceOptions.SectionName)
{
if (services == null)
throw new ArgumentNullException(nameof(services));
if (string.IsNullOrWhiteSpace(clientName))
throw new ArgumentNullException(nameof(clientName));
if (configuration == null)
throw new ArgumentNullException(nameof(configuration));
if (configureHttpClient == null)
throw new ArgumentNullException(nameof(configureHttpClient));
services.AddMudHttpClient(clientName, configureHttpClient);
services.AddMudHttpResilienceDecorator(configuration, resilienceSectionPath);
return services;
}
/// <summary>
/// 一站式注册 Mud.HttpUtils 服务,带 AES 加密配置。
/// </summary>
/// <param name="services">服务集合。</param>
/// <param name="clientName">Named HttpClient 的名称。</param>
/// <param name="configureEncryption">配置 AES 加密选项的委托。</param>
/// <param name="configureHttpClient">配置 HttpClient 的委托。</param>
/// <param name="configureResilienceOptions">配置弹性策略选项的委托(可选)。</param>
/// <returns>服务集合(链式调用)。</returns>
/// <exception cref="ArgumentNullException">参数为 null 时抛出。</exception>
public static IServiceCollection AddMudHttpUtils(
this IServiceCollection services,
string clientName,
Action<AesEncryptionOptions> configureEncryption,
Action<HttpClient> configureHttpClient,
Action<ResilienceOptions>? configureResilienceOptions = null)
{
if (services == null)
throw new ArgumentNullException(nameof(services));
if (configureEncryption == null)
throw new ArgumentNullException(nameof(configureEncryption));
services.AddMudHttpClient(clientName, configureEncryption, configureHttpClient);
if (configureResilienceOptions != null)
{
services.AddMudHttpResilienceDecorator(configureResilienceOptions);
}
return services;
}
#endregion
private sealed class ResilienceDecoratorPostConfigure : IPostConfigureOptions<EnhancedHttpClientFactoryOptions>
{
public void PostConfigure(string? name, EnhancedHttpClientFactoryOptions options)
{
var keys = options.ClientFactories.Keys.ToList();
foreach (var key in keys)
{
var originalFactory = options.ClientFactories[key];
options.ClientFactories[key] = sp =>
{
var inner = originalFactory(sp);
return CreateResilientDecorator(inner, sp);
};
}
}
}
}