Unable to resolve dependency HttpClient in net.core 3.0

1.5k views Asked by At

I'm trying to use IHttpClientFactory. I've read the article https://learn.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?view=aspnetcore-3.0 Startup.cs

public void ConfigureServices(IServiceCollection services)
        {
            services.AddHttpClient();
            services.AddSingleton<INasaStream, NasaStream>();
            services.AddSingleton<INasaProvider, NasaProvider>();
        }
// another methods remove for clearance

NasaStream.cs

public class NasaStream : INasaStream
    {
 // some variables declaration
        public NasaStream(IOptions<AppSettings> options, HttpClient _client, ILogger<NasaProvider> _logger)
        {
            settings = options.Value;
            client = _client;
            logger = _logger;
        }
}

There is no error with compilation. But when I try to run my app, there is an error:

Unhandled exception. System.AggregateException: Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: Mars.INasaStream Lifetime: Singleton ImplementationType: Mars.NasaStream': Unable to resolve service for type 'System.Net.Http.HttpClient' while attempting to activate 'Mars.NasaStream'.) (Error while validating the service descriptor 'ServiceType: Mars.INasaProvider Lifetime: Singleton ImplementationType: Mars.NasaProvider': Unable to resolve service for type 'System.Net.Http.HttpClient' while attempting to activate 'Mars.NasaStream'.) (Error while validating the service descriptor 'ServiceType: Mars.SolDataQuery Lifetime: Singleton ImplementationType: Mars.SolDataQuery': Unable to resolve service for type 'System.Net.Http.HttpClient' while attempting to activate 'Mars.NasaStream'.)

Why do I do wrong?

1

There are 1 answers

0
Galina Melnik On

Ok, that's was my mistake. I couldn't see errors and debug log because I switched them off. It didn't mean that my code not work. Correct answer was done by @Nkosi

public void ConfigureServices(IServiceCollection services)
    {

        services.AddHttpClient<INasaStream, NasaStream>();
        ...
    }

I should use typed client, that's all