C#C
C#3y ago
oe

Refactoring Injected Singleton for Authentication and HttpClient Usage

Everytime a 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:

var builder = WebApplication.CreateBuilder(args);
...
builder.Services.AddSingleton(await TestPaymentsService.CreateAsync());
...
builder.Services.AddHttpClient();


TestPaymentsService.cs:

public class TestPaymentsService
{
    private string? jwtToken { get; set; }

    public static async Task<TestPaymentsService> CreateAsync()
    {
        var client = new TestPaymentsService();
        await client.Authenticate();
        return client;
    }
...
public async Task Authenticate()
{
    using var client = new HttpClient();
...
Was this page helpful?