'ASP.NET Core Web API - Cannot instantiate implementation type 'System.Net.Http.IHttpClientFactory' for service type

I am trying to use Dependency Injection to register service in ASP.NET Core-6 Web API.

I got this interface:

public interface IHttpClientService
{
    Task<TRes> PostRequestAsync<TReq, TRes>(string baseUrl, string requestUrl, TReq requestModel, string token = null)
        where TRes : class
        where TReq : class;
    Task<TRes> GetRequestAsync<TRes>(string baseUrl, string requestUrl, string token = null)
        where TRes : class;
}

and also the implementation:

public class HttpClientService : IHttpClientService
{
    private readonly IHttpClientFactory _clientFactory;

    public HttpClientService(IHttpClientFactory clientFactory)
    {
        _clientFactory = clientFactory;
    }
    public async Task<TRes> GetRequestAsync<TRes>(string baseUrl, string url, string token = null) where TRes : class
    {
        var client = CreateClient(baseUrl, token);
        var request = new HttpRequestMessage(HttpMethod.Get, url);
        return await GetResponseResultAsync<TRes>(client, request);
    }

    public async Task<TRes> PostRequestAsync<TReq, TRes>(string baseUrl, string url, TReq requestModel, string token = null)
        where TRes : class
        where TReq : class
    {
        var client = CreateClient(baseUrl, token);
        var request = new HttpRequestMessage(HttpMethod.Post, url)
        {
            Content = new StringContent(JsonConvert.SerializeObject(requestModel), null, "application/json")
        };
        return await GetResponseResultAsync<TRes>(client, request);
    }

    private async Task<TRes> GetResponseResultAsync<TRes>(HttpClient client, HttpRequestMessage request) where TRes : class
    {
        var response = await client.SendAsync(request);
        var responseString = await response.Content.ReadAsStringAsync();
        var result = JsonConvert.DeserializeObject<TRes>(responseString);
        return response.IsSuccessStatusCode ? result : throw new ArgumentException(response.ReasonPhrase);
    }
    private HttpClient CreateClient(string baseUrl, string token)
    {
        var client = _clientFactory.CreateClient();
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        client.BaseAddress = new Uri(baseUrl);
        if (!string.IsNullOrEmpty(token))
        {
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
        }
        return client;
    }
}

Then for the DI, I did this:

services.AddScoped<IHttpClientService, HttpClientService>();
services.AddScoped<IHttpClientFactory, IHttpClientFactory>();

Initially, the error was:

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

But when I added:

services.AddScoped<IHttpClientFactory, IHttpClientFactory>();

It became:

System.ArgumentException
  HResult=0x80070057
  Message=Cannot instantiate implementation type 'System.Net.Http.IHttpClientFactory' for service type 'System.Net.Http.IHttpClientFactory'.
  Source=Microsoft.Extensions.DependencyInjection
  StackTrace:
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.Populate()
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory..ctor(ICollection`1 descriptors)
   at Microsoft.Extensions.DependencyInjection.ServiceProvider..ctor(ICollection`1 serviceDescriptors, ServiceProviderOptions options)
   at Microsoft.Extensions.DependencyInjection.ServiceCollectionContainerBuilderExtensions.BuildServiceProvider(IServiceCollection services, ServiceProviderOptions options)
   at Microsoft.Extensions.DependencyInjection.DefaultServiceProviderFactory.CreateServiceProvider(IServiceCollection containerBuilder)
   at Microsoft.Extensions.Hosting.Internal.ServiceFactoryAdapter`1.CreateServiceProvider(Object containerBuilder)
   at Microsoft.Extensions.Hosting.HostBuilder.CreateServiceProvider()
   at Microsoft.Extensions.Hosting.HostBuilder.Build()
   at Microsoft.AspNetCore.Builder.WebApplicationBuilder.Build()
   at Program.<<Main>$>d__0.MoveNext() in C:\MyApp.WebApi\Program.cs:line 165

I have tried to check the code again, but couldn't trace the error. What else do I need to do and how do I resolve this error?

Thanks



Solution 1:[1]

services.AddHttpClient();

Extension method found under Microsoft.Extensions.DependencyInjection.

Solution 2:[2]

Can you try this?

services.AddScoped<IHttpClientFactory, IHttpClientFactory>();
services.AddScoped<IHttpClientService, HttpClientService>(sp => {
  sp.GetRequiredService<IHttpClientFactory>();
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 CER
Solution 2 mehmetcantas