Can I use HttpClientFactory in a .NET.core app which is not ASP.NET Core?

前端 未结 4 617
悲&欢浪女
悲&欢浪女 2021-01-07 21:45

I have read the popular blog post https://www.stevejgordon.co.uk/introduction-to-httpclientfactory-aspnetcore on using HttpClientFactory

To quote from it

4条回答
  •  误落风尘
    2021-01-07 22:36

    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();
      ServiceCollection.AddScoped();
      
    • register your HttpClient to use HttpClientFactory

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

      var client = ServiceProvider.GetService();
      

提交回复
热议问题