From 62bd1f46200bd04dfa48709ac3c6dbb1993dd6c6 Mon Sep 17 00:00:00 2001 From: Tom Sloboda Date: Fri, 15 Mar 2024 10:34:51 +0000 Subject: [PATCH] Added HttpClientFactory to reuse HttpClient --- src/GeoblockingMiddleware/Common.fs | 8 ++++++-- src/GeoblockingMiddleware/GeoblockingMiddleware.fsproj | 4 ++++ 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/src/GeoblockingMiddleware/Common.fs b/src/GeoblockingMiddleware/Common.fs index 5a3500d..1915dbb 100644 --- a/src/GeoblockingMiddleware/Common.fs +++ b/src/GeoblockingMiddleware/Common.fs @@ -4,6 +4,7 @@ open System open System.Net.Http open Newtonsoft.Json open System.Collections.Concurrent +open Microsoft.Extensions.DependencyInjection type IpApiModel = { status: string; countryCode: string } @@ -55,13 +56,16 @@ module Common = TimeoutMs = 5000 Service = Ip_Api } + let services = new ServiceCollection() + let httpClientFactory = services.AddHttpClient().BuildServiceProvider().GetService() + /// Keep in memory a list of the latest ip addresses with their blocking status. /// This is public so it can be cleaned with scheduled task outside of this library. let lastIpAddressesCache = ConcurrentDictionary() let serviceCallIpApi (ipAddress: string) timeout = task { - use httpClient = new HttpClient(Timeout = TimeSpan.FromMilliseconds timeout) + let httpClient = httpClientFactory.CreateClient(Timeout = TimeSpan.FromMilliseconds timeout) let! json = httpClient.GetStringAsync($"http://ip-api.com/json/{ipAddress}?fields=status,countryCode") @@ -76,7 +80,7 @@ module Common = let serviceCallIpInfo (token: string) (ipAddress: string) timeout = task { - use httpClient = new HttpClient(Timeout = TimeSpan.FromMilliseconds timeout) + let httpClient = httpClientFactory.CreateClient(Timeout = TimeSpan.FromMilliseconds timeout) httpClient.DefaultRequestHeaders.Accept.Add( System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json") diff --git a/src/GeoblockingMiddleware/GeoblockingMiddleware.fsproj b/src/GeoblockingMiddleware/GeoblockingMiddleware.fsproj index 3526a13..b7a16a0 100644 --- a/src/GeoblockingMiddleware/GeoblockingMiddleware.fsproj +++ b/src/GeoblockingMiddleware/GeoblockingMiddleware.fsproj @@ -55,5 +55,9 @@ + + + +