I am trying the most simple IHttpClientFactory use case
public interface IWeatherForecast
{
    Task<string> Get();
}
class WeatherForecast : IWeatherForecast
{
    private readonly HttpClient httpClient;
    public WeatherForecast (IHttpClientFactory httpClientFactory)
    {
        httpClient = httpClientFactory.CreateClient();
    }
    public async Task<string> Get()
    {
        var resp = await httpClient.GetAsync("https://testwebapiforuseinsamples.azurewebsites.net/weatherforecast");
        return JsonConvert.SerializeObject(resp.Content.ReadAsStringAsync());
    }
}
and then instantiate it
static async Task Main(string[] args)
{
    var container = new ServiceCollection();
    container.AddHttpClient<IWeatherForecast, WeatherForecast>();
    var serviceProvider = container.BuildServiceProvider();    
    var resp = await serviceProvider.GetRequiredService<WeatherForecast>().Get();
}
However when I run it, it throws
System.InvalidOperationException: 'A suitable constructor for type 'HttpClientFactoryExample.WeatherForecast' could not be located. Ensure the type is concrete ...
Can someone point it what is wrong with this code. I was expecting that after adding WeatherForecast service to DI, I will be able to get an initialized instance of it from the container.
When you register type in Service collection as HTTP client container.AddHttpClient<IWeatherForecast, WeatherForecast>(), it MUST contains HttpClient in constructor. In your case it should be:
public WeatherForecast(HttpClient httpClient)
{
     this.httpClient = httpClient;
}
Another option is to register separately the HttpClientFactory and your WeatherForecast service:
container.AddHttpClient();
container.AddTransient<IWeatherForecast, WeatherForecast>();
and then use the service with HttpClientFactory:
private readonly HttpClient httpClient;
public WeatherForecast(IHttpClientFactory factory)
{
    this.httpClient = factory.CreateClient();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With