0

I have the below Generic Class & Interface implementations

public interface IHttpClient<T> where T : class
{
   public Task<List<T>> GetJsonAsync(string url);
}


public class HttpClient<T> : IHttpClient<T> where T:class
{
    private readonly IHttpClientFactory _clientFactory;

    public HttpClient(IHttpClientFactory clientFactory)
    {
        _clientFactory = clientFactory;
    }

  

    public async Task<List<T>> GetJsonAsync(string url)
    {
        var request = new HttpRequestMessage(HttpMethod.Get,url);
        var client = _clientFactory.CreateClient();

        var response = await client.SendAsync(request);

        if (response.IsSuccessStatusCode)
        {
            var result = await response.Content.ReadAsStringAsync();
            return JsonConvert.DeserializeObject<List<T>>(result);
        }

        return null;
    }
     
}

and this is how I try to register them in the startup.cs

 public void ConfigureServices(IServiceCollection services)
 {      
     services.AddScoped(typeof(IHttpClient<>), typeof(HttpClient<>));
 }

My Controller:

  private readonly IHttpClient<Feed> _feedClient;
  public HomeController( IHttpClient<Feed> _client)
    {
       
        _feedClient = _client;

      
    }

and this is the error I'm getting

InvalidOperationException: Unable to resolve service for type 'System.Net.Http.IHttpClientFactory' while attempting to activate...

what is it that I'm missing? any help is very appreciated..

3
  • Seems you did not register your IHttpClientFactory in IoC Commented Jul 30, 2020 at 13:24
  • 1
    Also add services.AddHttpClient(); Commented Jul 30, 2020 at 13:24
  • Thank you Knoop, it worked smoothly after adding the code =)) Commented Jul 30, 2020 at 13:33

1 Answer 1

1

You should register HttpClient in startup class like this

//register
services.AddHttpClient();

use

public YourController(IHttpClientFactory httpClientFactory)
{ 
    _httpClientFactory = httpClientFactory;
}
var client = _httpClientFactory.CreateClient();

Another options

//register
services.AddHttpClient("YourClientName", c =>
{
    c.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    c.BaseAddress = new Uri("https://yoururl");
});

use

public YourController(IHttpClientFactory httpClientFactory)
{ 
    _httpClientFactory = httpClientFactory;
}
var client = _httpClientFactory.CreateClient("YourClientName");
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.