Results 1 to 5 of 5

Thread: Inject IHttpClientFactory To Create HttpClient through a class

  1. #1

    Thread Starter
    Fanatic Member
    Join Date
    Nov 2003
    Posts
    782

    Inject IHttpClientFactory To Create HttpClient through a class

    Hello,

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

    program.cs

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

    Code:
        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();
            }
        }
    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.***"

    WeatherForecastController.cs


    Code:
        public WeatherForecastController(IWeatherService weatherService)
        {
             _weatherService = weatherService;
        }
    
        [HttpGet]
        public async Task<string> Get(string cityName)
        {
            return await _weatherService.Get(cityName);
        }
    Question:

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

    Class1 class1 = new Class1();

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

  2. #2
    Fanatic Member
    Join Date
    Jun 2019
    Posts
    557

    Re: Inject IHttpClientFactory To Create HttpClient through a class

    Use the DI container to get instance of the service:

    C# Code:
    1. using var scope = app.Services.CreateScope();
    2. var services = scope.ServiceProvider;
    3. var weatherService = services.GetRequiredService<IWeatherService>();
    where app is WebApplication.

    Then just inject it when creating the object.

  3. #3

    Thread Starter
    Fanatic Member
    Join Date
    Nov 2003
    Posts
    782

    Re: Inject IHttpClientFactory To Create HttpClient through a class

    Hi @peterst,
    thank you, I have tried this:


    Code:
                
                var app = WebApplication.Create();
                
                using var scope = app.Services.CreateScope();
                var services = scope.ServiceProvider;
                var weatherService = services.GetRequiredService<ITest>();
    it returns No service for type 'Learning.Models.ITest' has been registered.

    program.cs

    Code:
                
    builder.Services.AddHttpClient<Learning.Models.ITest, Learning.Models.Test>("test", c1 =>
    {
        c1.BaseAddress = new Uri("https://xxx.xxxxx.com/api");
        c1.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        c1.DefaultRequestHeaders.CacheControl = new CacheControlHeaderValue { NoCache = true };
        c1.Timeout = TimeSpan.FromMinutes(3);
    })
    Last edited by Winanjaya; Feb 6th, 2023 at 07:42 AM.

  4. #4
    Fanatic Member
    Join Date
    Jun 2019
    Posts
    557

    Re: Inject IHttpClientFactory To Create HttpClient through a class

    You must register your services first if you want to get them from the DI (dependency injection) container. But first read what dependency injection is and why it is used. It will help you understand the workflow.

  5. #5

    Thread Starter
    Fanatic Member
    Join Date
    Nov 2003
    Posts
    782

    Re: Inject IHttpClientFactory To Create HttpClient through a class

    I had it:

    Code:
    builder.Services.AddSingleton<Learning.Models.ITest, Learning.Models.Test>();

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width