I have read the popular blog post https://www.stevejgordon.co.uk/introduction-to-httpclientfactory-aspnetcore on using HttpClientFactory
To quote from it
A new HttpClientFactory feature is coming in ASP.NET Core 2.1 which helps to solve some common problems that developers may run into when using HttpClient instances to make external web requests from their applications.
All the examples show wiring it up in startup class of asp.net application e.g.
public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); services.AddHttpClient(); }
My question is can you use outside of ASP.NET core? And if so are there examples
I would have thought lots of non web applications(.net core apps) need to make web calls, so why was this not part of .net core api instead of putting into asp.net core api
Not only that HttpClientFactory can create and manage new HttpClient instances but also, it works with underlying handlers. Basically, when creating new HttpClient instances, it doesn't recreate a new message handler but it takes one from a pool. Then, it uses that message handler to send the requests to the API.
It has a method CreateClient which returns the HttpClient Object. But in reality, HttpClient is just a wrapper, for HttpMessageHandler. HttpClientFactory manages the lifetime of HttpMessageHandelr, which is actually a HttpClientHandler who does the real work under the hood.
NET Core is a runtime. It can execute applications that are built for it. ASP.NET Core is a collection of libraries that form a Framework for building web applications.
In order to run ASP.NET Core Apps on the . NET Framework it needs to only reference . Core NuGet packages which contains only the . NET Standard 2.0 builds.
According to the documentation HttpClientFactory is a part of .Net Core 2.1, so you don't need ASP.NET to use it. And there some ways to use are described. The easiest way would be to use Microsoft.Extensions.DependencyInjection with AddHttpClient
extension method.
static void Main(string[] args) { var serviceProvider = new ServiceCollection().AddHttpClient().BuildServiceProvider(); var httpClientFactory = serviceProvider.GetService<IHttpClientFactory>(); var client = httpClientFactory.CreateClient(); }
Thanks for replies.
So it is possible to use in console app.
There are a few ways to do this, depending on what way you want to go. Here are 2:
Directly add to ServiceCollection e.g. services.AddHttpClient()
Use Generic host e.g. Add httpclientFactory in .ConfigureServices() method
See here for blog post using in console app
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With