Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A suitable constructor of type does not be located

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.

like image 862
Tauqir Avatar asked Sep 17 '25 18:09

Tauqir


1 Answers

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();
}
like image 152
Yaroslav Bres Avatar answered Sep 19 '25 07:09

Yaroslav Bres