Inject IHttpClientFactory To Create HttpClient through a class

winanjaya 146 Reputation points
2023-02-06T07:30:50.62+00:00

I'm trying to Use IHttpClientFactory To Create HttpClient (ref: https://www.rahulpnath.com/blog/are-you-using-httpclient-in-the-right-way/).

At the end of the page, it says:

"The Controller class can now use the WeatherService and call it to get back the relevant data, as shown below."

What if we don't use Controller class but we want to use a class?, like:

Class1 class1 = new Class1();

How to inject the service and call the interface (in my case it's Task Get(string cityName);)

program.cs

services.AddHttpClient<IWeatherService,WeatherService>(c => {
      c.BaseAddress = new Uri("http://api.weatherapi.com/v1/current.json");
    });


builder.Services.AddSingleton<ITest, Test>();
builder.Services.AddHttpClient<ITest, Test>("test", c1 =>
{
    c1.BaseAddress = new Uri("https://test.xxxxx.com/api");
    c1.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    c1.DefaultRequestHeaders.CacheControl = new CacheControlHeaderValue { NoCache = true };
    c1.Timeout = TimeSpan.FromMinutes(3);
});

 

    
    public interface IWeatherService
    {
        Task <string> Get(string cityName);
    }

    public class WeatherService: IWeatherService
    {
        private HttpClient _httpClient;

        public WeatherService(HttpClient httpClient)
        {
            _httpClient = httpClient;
        }

        public async Task < string > Get(string cityName)
        {
            string APIURL = $ "?key={API_KEY}&q={cityName}";
            var response = await _httpClient.GetAsync(APIURL);
            return await response.Content.ReadAsStringAsync();
        }
    }

WeatherForecastController.cs

    public WeatherForecastController(IWeatherService weatherService)
    {
         _weatherService = weatherService;
    }

    [HttpGet]
    public async Task<string> Get(string cityName)
    {
        return await _weatherService.Get(cityName);
    }
    {
        Task<string[]> RunAsync(object parameters);
    }

    public class Test : ITest
    {
        private readonly IHttpClientFactory _httpClientFactory = null!;
        public Test(IHttpClienFactory httpClientFactory)
        {
            _httpClientFactory= httpClientFactory;
        }

        public async Task<string[]> RunAsync(object parameters)
        {
            object[] parameterArray = (object[])parameters;

            string token = (string)parameterArray[0];

            var tasks = new List<Task<string>>();

            _httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Token", token);
  
            bool _break = false;
            do
            {
 	   	   await _httpClient.GetAsync(url).ContinueWith(async (c) =>
               {
                   var response = await c;

                   if (response.IsSuccessStatusCode)
                   {
                       tasks.Add(response.Content.ReadAsStringAsync());
                   }
                   else
                       _break = true;
               });
             } while(_break=false);.
             
         }
         return await Task.FromResult(tasks)
     }
  }


ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,530 questions
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,463 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,863 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 64,651 Reputation points
    2023-02-06T16:16:39.66+00:00

    typically you would pass a HttpClient to the class constructor:

    Class1 class1 = new Class1(httpclient);

    if called from a controller, use the injected HttpClient.

    1 person found this answer helpful.

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.