Unable to resolve service for type 'System.Net.Http.HttpClient' while attempting to activate... error

Problem

When I tried to register a service that uses an object of System.Net.Http.HttpClient  for dependency injection, I got the following error. 

AggregateException: Some services are not able to be constructed (Error while validating the 
service descriptor 'ServiceType: APICallHelper.IHttpService Lifetime: Scoped ImplementationType:
APICallHelper.HttpService': Unable to resolve service for type 'System.Net.Http.HttpClient' while
attempting to activate 'APICallHelper.HttpService'.)

IHttpService.cs
namespace APICallHelper
{
    public class HttpService : IHttpService
    {
        private readonly HttpClient httpClient;

       
        public HttpService(HttpClient httpClient)
        {
            this.httpClient = httpClient;
        }

        public async Task<HttpResponseWrapper<T>> Get<T>(string url)
        {
            var responseHTTP = await httpClient.GetAsync(url);

            if (responseHTTP.IsSuccessStatusCode)
            {
                var response = await Deserialize<T>(responseHTTP, defaultJsonSerializerOptions);
                return new HttpResponseWrapper<T>(response, true, responseHTTP);
            }
            else
            {
                return new HttpResponseWrapper<T>(default, false, responseHTTP);
            }
        }
  }
}

IHttpService.cs

namespace APICallHelper
{
    public interface IHttpService
    {       
        Task<HttpResponseWrapper<T>> Get<T>(string url);
    }
}

Startup.cs

 public void ConfigureServices(IServiceCollection services)
        {                 
           services.AddScoped<IHttpService, HttpService>();
            
        }

 

Solution

The error was fixed when I use the following code to register the service for dependency injection in the startup file.

public void ConfigureServices(IServiceCollection services)
        {          
            services.AddHttpClient<IHttpService, HttpService>();           
        }

Registering the client service as shown above, makes the DefaultClientFactory create a standard HttpClient for the service.


Search