Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't use AddHttpClient / IHttpClientBuilder in console app

I have some code from a web app that configures the http client to use a certificate. I relies on IHttpClientBuilder and AddHttpClient.

I'd like to use the same methods for testing in a console app, but I'm struggling to even get those types be available there.

The documentation here says I can use Microsoft.Extensions.Hosting in a console app (there it's used to initialize configuration), but even though this package is supposed to depend on Microsoft.Extensions.DependencyInjection, where above types and methods are supposed to live, the compiler tells me those types are unknown.

The console app is freshly created with .NET 6.0 and it's only package reference is Microsoft.Extensions.Hosting at 6.0.1. Why does that not give me IHttpClientBuilder?

EDIT:

After

dotnet new console
dotnet add package Microsoft.Extensions.Hosting

edit only Program.cs to

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

var host = Host.CreateDefaultBuilder(args);

host.ConfigureServices(services =>
{
    services.AddHttpClient(); // not found
});

to find that IHttpClientBuilder and friends are still not there.

like image 362
John Avatar asked Mar 24 '26 17:03

John


1 Answers

You need to add a reference to the Microsoft.Extensions.Http package, in addition to Microsoft.Extensions.DependencyInjection.

I had the exact same problem and the Microsoft documentation I read didn't mention this explicitly. It became obvious when I read this blog post: Simple Example of Calling REST API with HttpClient in .NET 5.0 by Adam Storr. In it, the author adds both packages.

On re-reviewing the documentation for the HttpClientFactoryServiceCollectionExtensions, I noticed under the "Definition" header that the namespace is Microsoft.Extensions.DependencyInjection but the assembly is Microsoft.Extensions.Http.dll.

like image 138
grokmann Avatar answered Mar 26 '26 15:03

grokmann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!