Refactoring Injected Singleton for Authentication and HttpClient Usage
Everytime a
Instead of firing off a web request in the constructor (since it cannot be async), I decided to create a static create method that creates the instance to be able to authenticate.
However, I now realised its a bad practice to recreate a HttpClient in every method inside
I want to be able to create a
How should I approach this? Current implementation:
Program.cs:
TestPaymentsService.cs:
TestPaymentsService is created, it should be authenticated. Instead of constantly calling .Authenticate, I want to be able to do it once at the start of my app's lifetime.Instead of firing off a web request in the constructor (since it cannot be async), I decided to create a static create method that creates the instance to be able to authenticate.
However, I now realised its a bad practice to recreate a HttpClient in every method inside
TestPaymentsService. Although I registered a IHttpClientFactory using builder.Services.AddHttpClient(); in Program.cs, I cannot inject it since I dont have a constructor. I want to be able to create a
TestPaymentsService, inject it into DI and use it wherever I want without having to call Authenticate method each time, since it was called at the very beginning. How should I approach this? Current implementation:
Program.cs:
TestPaymentsService.cs: