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:
- create a
ServiceCollection
- call the
AddHttpClient
- build it to have a
ServiceProvider
- 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