I'm using an ASP.NET MVC application on .NET 4.8. In doing so, I'm consuming APIs from three separate partners. Each time an API call is made, an new instance of the HttpClient
is created in the controller and invoked via an ajax call from the view page.
My question is that, even though we can develop using third-party packages like UNITY, we are unable to create dependency injection because this is an ASP.NET MVC application rather than an ASP.NET Core application.
How can I accomplish reusing a HttpClient
instance across my program instead of utilizing dependency injection?
Due to the fact that the majority of articles mentioned that bad performance and socket exhaustion result from establishing new HttpClient
instances. This is my API call code and also consider this API will be called lot throughout the day.
Code:
var client = new HttpClient();
HttpResponseMessage response = null;
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Ssl3
| System.Net.SecurityProtocolType.Tls
| System.Net.SecurityProtocolType.Tls11
| System.Net.SecurityProtocolType.Tls12;
var content = JsonConvert.SerializeObject(ModelObj, settings);
byte[] buffer = Encoding.ASCII.GetBytes(content);
var bytecontent = new ByteArrayContent(buffer);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
response = client.PostAsync(URL,bytecontent).Result;
I need to reuse HttpClient
instance throughout my application without using Dependency Injection container in ASP.NET MVC on .NET 4.8.
You can implement a pattern like the Singleton pattern to manage and reuse the HttpClient
instance across your application.
Create a static class that manages the HttpClient
instance:
public static class HttpClientHelper
{
private static readonly Lazy<HttpClient> httpClientInstance = new Lazy<HttpClient>(() =>
{
var httpClient = new HttpClient();
// Set your desired SecurityProtocol
System.Net.ServicePointManager.SecurityProtocol =
System.Net.SecurityProtocolType.Tls12 |
System.Net.SecurityProtocolType.Tls11 |
System.Net.SecurityProtocolType.Tls;
return httpClient;
});
public static HttpClient GetInstance()
{
return httpClientInstance.Value;
}
}
Then, in your controller or wherever you make API calls, you can use this HttpClientHelper
class to get the singleton HttpClient
instance:
var client = HttpClientHelper.GetInstance();
var content = JsonConvert.SerializeObject(ModelObj, settings);
byte[] buffer = Encoding.ASCII.GetBytes(content);
var bytecontent = new ByteArrayContent(buffer);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = client.PostAsync(URL, bytecontent).Result;
Please note that above code can help issues associated with creating multiple instances, but you have to handle the HttpClient
properly, including managing its lifetime and ensuring proper disposal when it's no longer needed.