1+ using System . Net ;
12using System . Net . Http . Headers ;
23using Microsoft . Extensions . DependencyInjection ;
4+ using Polly ;
5+ using Polly . Extensions . Http ;
36
47namespace Cnblogs . Architecture . Ddd . Cqrs . ServiceAgent ;
58
@@ -13,38 +16,53 @@ public static class InjectExtensions
1316 /// </summary>
1417 /// <param name="services">The <see cref="IServiceCollection"/>.</param>
1518 /// <param name="baseUri">The base uri for api.</param>
16- /// <typeparam name="T">The type of service agent</typeparam>
19+ /// <param name="policy">The polly policy for underlying httpclient.</param>
20+ /// <typeparam name="TClient">The type of service agent</typeparam>
1721 /// <returns></returns>
18- public static IHttpClientBuilder AddServiceAgent < T > ( this IServiceCollection services , string baseUri )
19- where T : CqrsServiceAgent
22+ public static IHttpClientBuilder AddServiceAgent < TClient > (
23+ this IServiceCollection services ,
24+ string baseUri ,
25+ IAsyncPolicy < HttpResponseMessage > ? policy = null )
26+ where TClient : class
2027 {
21- return services . AddHttpClient < T > (
28+ policy ??= GetDefaultPolicy ( ) ;
29+ return services . AddHttpClient < TClient > (
2230 h =>
2331 {
2432 h . BaseAddress = new Uri ( baseUri ) ;
2533 h . DefaultRequestHeaders . Accept . Add ( new MediaTypeWithQualityHeaderValue ( "application/cqrs" ) ) ;
26- } ) ;
34+ } ) . AddPolicyHandler ( policy ) ;
2735 }
2836
2937 /// <summary>
3038 /// Inject a service agent to services.
3139 /// </summary>
3240 /// <param name="services">The <see cref="IServiceCollection"/>.</param>
3341 /// <param name="baseUri">The base uri for api.</param>
42+ /// <param name="policy">The polly policy for underlying httpclient.</param>
3443 /// <typeparam name="TClient">The type of api client.</typeparam>
3544 /// <typeparam name="TImplementation">The type of service agent</typeparam>
3645 /// <returns></returns>
3746 public static IHttpClientBuilder AddServiceAgent < TClient , TImplementation > (
3847 this IServiceCollection services ,
39- string baseUri )
48+ string baseUri ,
49+ IAsyncPolicy < HttpResponseMessage > ? policy = null )
4050 where TClient : class
41- where TImplementation : CqrsServiceAgent , TClient
51+ where TImplementation : class , TClient
4252 {
53+ policy ??= GetDefaultPolicy ( ) ;
4354 return services . AddHttpClient < TClient , TImplementation > (
4455 h =>
4556 {
4657 h . BaseAddress = new Uri ( baseUri ) ;
4758 h . DefaultRequestHeaders . Accept . Add ( new MediaTypeWithQualityHeaderValue ( "application/cqrs" ) ) ;
48- } ) ;
59+ } ) . AddPolicyHandler ( policy ) ;
60+ }
61+
62+ private static IAsyncPolicy < HttpResponseMessage > GetDefaultPolicy ( )
63+ {
64+ return HttpPolicyExtensions . HandleTransientHttpError ( )
65+ . OrResult ( msg => msg . StatusCode == HttpStatusCode . TooManyRequests )
66+ . WaitAndRetryAsync ( 3 , _ => TimeSpan . FromMilliseconds ( 1500 ) ) ;
4967 }
5068}
0 commit comments