This is a made up scenario and I want to find the best way of implementing and learn which are the best practices.
I am writing a service that makes a get request to an api which requires an Authorization header, the problem is that I am initializing a new client for each service, I was thinking if it is the best to have a singleton client and use that anywhere in different services.
Here I have my BlogService, where I initialize the client and then add the Authorization header, username and password will be in configs but this is just an example.
namespace MyDemoProject.Services
{
public class BlogService : IBlogService
{
private readonly HttpClient client;
private string username = "myUsername";
private string password = "myPassword";
private static string url = "https://example.com/api/blogs";
public BlogService()
{
client = new HttpClient();
string encoded = System.Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password));
client.DefaultRequestHeaders.Add("Authorization", "Basic " + encoded);
}
public async Task<string> GetAllBlogs()
{
var request = await client.GetAsync(url);
var data = await request.Content.ReadAsStringAsync();
return data;
}
}
}
And here I have my CommentService, which is very similar, but with a different url. This is a simple example and it could be included in the same BlogService, but suppose that I want to make it granular for maintainability and scalability.
namespace MyDemoProject.Services
{
public class CommentService : ICommentService
{
private readonly HttpClient client;
private string username = "myUsername";
private string password = "myPassword";
private static string url = "https://example.com/api/comments";
public CommentService()
{
client = new HttpClient();
string encoded = System.Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password));
client.DefaultRequestHeaders.Add("Authorization", "Basic " + encoded);
}
public async Task<string> GetAllComments()
{
var request = await client.GetAsync(url);
var data = await request.Content.ReadAsStringAsync();
return data;
}
}
}
Is there any better way of implementing this, and are there any issues with this implementation?
>();`