'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.
Solution 1:[1]
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
.
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 | grokmann |