66using System . Net . Http ;
77using System . Net . Security ;
88using System . Security . Cryptography . X509Certificates ;
9+ using System . Threading ;
910using Microsoft . Identity . Client . Http ;
1011using Microsoft . Identity . Client . ManagedIdentity ;
1112
@@ -24,8 +25,12 @@ internal class SimpleHttpClientFactory : IMsalMtlsHttpClientFactory, IMsalSFHttp
2425 private static readonly ConcurrentDictionary < string , HttpClient > s_httpClientPool = new ConcurrentDictionary < string , HttpClient > ( ) ;
2526 private static readonly object s_cacheLock = new object ( ) ;
2627
28+ // referenced in unit tests
29+ internal static int HttpClientCreationCount ;
30+
2731 private static HttpClient CreateHttpClient ( )
2832 {
33+ Interlocked . Increment ( ref HttpClientCreationCount ) ;
2934 CheckAndManageCache ( ) ;
3035
3136 var httpClient = new HttpClient ( new HttpClientHandler ( )
@@ -63,7 +68,7 @@ private static HttpClient CreateMtlsHttpClient(X509Certificate2 bindingCertifica
6368
6469 public HttpClient GetHttpClient ( )
6570 {
66- return s_httpClientPool . GetOrAdd ( "non_mtls" , CreateHttpClient ( ) ) ;
71+ return s_httpClientPool . GetOrAdd ( "non_mtls" , _ => CreateHttpClient ( ) ) ;
6772 }
6873
6974 public HttpClient GetHttpClient ( X509Certificate2 x509Certificate2 )
@@ -74,7 +79,7 @@ public HttpClient GetHttpClient(X509Certificate2 x509Certificate2)
7479 }
7580
7681 string key = x509Certificate2 . Thumbprint ;
77- return s_httpClientPool . GetOrAdd ( key , CreateMtlsHttpClient ( x509Certificate2 ) ) ;
82+ return s_httpClientPool . GetOrAdd ( key , _ => CreateMtlsHttpClient ( x509Certificate2 ) ) ;
7883 }
7984
8085 private static void CheckAndManageCache ( )
@@ -88,6 +93,13 @@ private static void CheckAndManageCache()
8893 }
8994 }
9095
96+ // referenced in unit tests
97+ internal static void ResetForTest ( )
98+ {
99+ s_httpClientPool . Clear ( ) ;
100+ HttpClientCreationCount = 0 ;
101+ }
102+
91103 // This method is used for Service Fabric scenarios where a custom server certificate validation callback is required.
92104 // It allows the caller to provide a custom HttpClientHandler with the callback.
93105 // The server cert rotates so we need a new HttpClient for each call.
0 commit comments