I haven't found any sample of registering a HttpClient singleton in a Windows Forms app, and the way it's done in ASP.NET Core does not seem to work here. On Form constructor, dependency injected httpClient gives null value. How can I get a singleton instance of HttpClient on Form1 Dependency Injection?
My Program.cs.Main():
[STAThread]
static void Main()
{
ApplicationConfiguration.Initialize();
var services = new ServiceCollection();
services.AddHttpClient();
services.AddScoped<Form1>();
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
var form1 = serviceProvider.GetRequiredService<Form1>();
Application.Run(form1);
}
}
My Form1:
public partial class Form1 : Form
{
[Inject] public HttpClient? http { get; set; }
public Form1()
{
InitializeComponent();
System.Diagnostics.Debug.WriteLine(http == null); // True
}
}
Finally got it working as follows:
Program.cs:
Form1: