A question that comes up when I'm programming when it comes to programming static classes.
Microsoft's official documentation says the following about static classes:
The static class can be used as a convenient container for sets of methods that just operate on input parameters and do not have to get or set any internal instance fields.
So here it says static classes can be used as a container for methods that only operate on input parameters and do not need to work with instance fields.
Let's now turn to a more specific problem. My ASP.NET application consumes a web service that will return me business-related information. To consume the web service I must do the authentication along with it, and after that send HTTP requests, simple, so I created a class, which I will call here ApiClient
.
At no point in the process do I need to access instance resources of the ApiClient
class, taking into account that data such as the endpoint URL, access key, and validity period of the access key will be the same for all users who consume the methods of class ApiClient
.
So far I imagine the choice in user a static class is correct. My question is the following, in case of multiple simultaneous calls of a method of class ApiClient
, if a request is delayed say 5 seconds, these requests would be queued, causing the static class to become a bottleneck in the consumption of the web service ?
Below is an example of the ApiClient
class I tried to describe.
public static class ApiClient
{
private static string baseUri = "http://baseuri.com";
private static async Task<string> GetKey()
{
//Get the key
}
private static async Task<string> SendRequest(string resource)
{
string key = await GetKey();
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("key", key);
string url = $"{baseUri}{resource}";
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, url);
HttpResponseMessage response = await client.SendAsync(request);
string result = await response.Content.ReadAsStringAsync();
return result;
}
public static async Task<CustomerInfo> GetCustomerInfo(string customerId)
{
string resource = $"/api/method/{customerId}";
string json = await SendRequest(resource);
CustomerInfo customerInfo = JsonConvert.DeserializeObject<CustomerInfo>(json);
return customerInfo;
}
}
Could this approach be considered problematic? In that case would I have a bottleneck problem if multiple requests are passed to the SendRequest
method? If yes, could this problem be solved by changing the approach and instantiation of the ApiClient
class?