34

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

havij
  • 1,030
  • 14
  • 29
Noel
  • 5,037
  • 9
  • 46
  • 69
  • I think someone has asked this before. Please take a look here and see if it's helpful to you: https://stackoverflow.com/questions/51498896/use-httpclientfactory-from-net-4-6-2 – Jason La Oct 03 '18 at 08:24
  • 1
    A blog post which addresses the question: https://nodogmablog.bryanhogan.net/2018/07/polly-httpclientfactory-and-the-policy-registry-in-a-console-application/ – mountain traveller Oct 04 '18 at 09:19

4 Answers4

53

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();
}
Alex Riabov
  • 8,655
  • 5
  • 47
  • 48
  • see link, only available in asp.net core https://learn.microsoft.com/en-gb/dotnet/api/system.net.http.ihttpclientfactory?view=aspnetcore-2.1 – Noel Oct 03 '18 at 09:23
  • 3
    @Noel, the provided code is for .Net Core console application. Also in your link Assembly: Microsoft.Extensions.Http.dll - so no connection to asp.net – Alex Riabov Oct 03 '18 at 09:38
  • 4
    AddHttpClient() is in the Microsoft.Extensions.Http nuget package – Bora Aydın Mar 30 '19 at 10:43
  • the documentation clearly states that projects targeting .NET Framework should install Microsoft.Extensions.Http nuget package, instead project targeting .NET Core should reference the Microsoft.AspNetCore.App metapackage which includes Microsoft.Extensions.Http package https://learn.microsoft.com/it-it/aspnet/core/fundamentals/http-requests?view=aspnetcore-2.2#prerequisites – refex Jun 26 '19 at 10:33
  • @refex it only means that Microsoft.AspNetCore.App metapackage includes Microsoft.Extensions.Http. But it doesn't mean that Microsoft.Extensions.Http package requires AspNetCore – Alex Riabov Jun 26 '19 at 11:31
  • 2
    Yeah you are right, I was able to use directly the Microsoft.Extensions.Http. was not so clear from the documentation, it advice to use the aspnet wrapper package – refex Jun 26 '19 at 18:45
  • I upvoted this. At the same time, havij answer provides a bettter way to "get at" the HttpClient in your codebase that is not "void Main". – granadaCoder Jun 23 '20 at 20:52
  • 3
    A newer version of the same scenario is here from Microsoft: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?view=aspnetcore-3.1#use-ihttpclientfactory-in-a-console-app – Rzassar Aug 11 '20 at 09:21
12

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:

  1. Directly add to ServiceCollection e.g. services.AddHttpClient()

  2. Use Generic host e.g. Add httpclientFactory in .ConfigureServices() method

See here for blog post using in console app

Noel
  • 5,037
  • 9
  • 46
  • 69
11

As one of the answers suggests,

you do not need ASP.NET to use it

However, you need a bit of work to get it into your Dependency Injection (DI):

  • Install microsoft.extensions.http (has nothing to do with ASP.NET)

  • When configuring your DI, use this extension. it registers builders/httpclientFactory/... (have a look at its source code on github)

    ServiceCollections.AddHttpClient();
    
  • if you want register HttpClient with different names/settings to communicate with different web servers (different settings, ex: different base urls)

    ServiceCollection.AddHttpClient(
    "yourClientName", x => x.BaseAddress = new Uri("http://www.mywebserver.com"))
    
  • In case you want to add DelegateHendlers, you need to add it both to your httpClient and your DI container.

    ServiceCollection
            .AddHttpClient(clientName, x => x.BaseAddress = new Uri("http://www.google.com"))
            .AddHttpMessageHandler<DummyDelegateHandler>();
    ServiceCollection.AddScoped<DummyDelegateHandler>();
    
  • register your HttpClient to use HttpClientFactory

    ServiceCollection.AddScoped<HttpClient>(x => 
    x.GetService<IHttpClientFactory>().CreateClient("yourClientName"));
    
  • To resolve http client:

    var client = ServiceProvider.GetService<HttpClient>();
    
Ali Abdoli
  • 529
  • 5
  • 9
1

Just providing sample code for the first suggested approach in the accepted answer:

services.AddHttpClient<IFoo, Foo>(); // where services is of type IServiceCollection

and your class looks like:

public class Foo : IFoo
{
    private readonly HttpClient httpClient;

    public Consumer(HttpClient httpClient)
    {
        this.httpClient = httpClient;
    }
}
havij
  • 1,030
  • 14
  • 29