1

I'm using .NET Framework 4.7.2 and am trying to use IHttpClientFactory to create HttpClient instances.

I downloaded the Microsoft.Extensions.Http v7 NuGet Package and now have access to System.Net.Http.HttpClientFactory.

Am I meant to use HttpClientFactory.Create() to create HttpClients?

Or do I have to use DI and IHttpClientFactory?

What is HttpClientFactory used for and why doesn't it implement IHttpClientFactory?

4
  • Have you had a chance to review this Commented Jan 10, 2023 at 3:09
  • @Nkosi I have. That article is for .NET Core and above. I'm using .NET Framework. Commented Jan 10, 2023 at 4:17
  • You should use the DefaultHttpClientFactory concrete class which implements the IHttpClientFactory interface. Commented Jan 11, 2023 at 16:59
  • @PeterCsala that's only available in .NET Core 2.1+. See learn.microsoft.com/en-us/dotnet/architecture/microservices/…. Commented Jan 11, 2023 at 20:32

1 Answer 1

1

I've checked the source code of the DefaultHttpClientFactory and even though it is part of the Microsoft.Extensions.Http namespace it is marked as internal.

Gladly the AddHttpClient extension method can do the DI registration of the above class on our behalf.

services.TryAddSingleton<DefaultHttpClientFactory>();
services.TryAddSingleton<IHttpClientFactory>(serviceProvider => serviceProvider.GetRequiredService<DefaultHttpClientFactory>());

So, all you need to do is:

  1. create a ServiceCollection
  2. call the AddHttpClient
  3. build it to have a ServiceProvider
  4. call the GetRequiredService

In order to do that in .NET Framework 4.7.2 you need to use the Microsoft.Extensions.DependencyInjection package.

using System;
using System.Net.Http;
using Microsoft.Extensions.DependencyInjection;

class Program
{
    private static readonly ServiceProvider serviceProvider;

    static Program()
    {
        serviceProvider = new ServiceCollection().AddHttpClient().BuildServiceProvider();
    }

    public static void Main(string[] args)
    {
        var factory = serviceProvider.GetRequiredService<IHttpClientFactory>();
        Console.WriteLine(factory == null); //False
    }
}

Here I have detailed how to do the same with SimpleInjector

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.