© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•3y ago•
2 replies
oe

Refactoring Injected Singleton for Authentication and HttpClient Usage

Everytime a
TestPaymentsService
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
TestPaymentsService
. Although I registered a
IHttpClientFactory
IHttpClientFactory
using
builder.Services.AddHttpClient();
builder.Services.AddHttpClient();
in
Program.cs
Program.cs
, I cannot inject it since I dont have a constructor.

I want to be able to create a
TestPaymentsService
TestPaymentsService
, inject it into DI and use it wherever I want without having to call
Authenticate
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();
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();
...
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();
...
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

Usage of AsyncLocal in singleton DI service to override authentication tokens
C#CC# / help
5mo ago
✅ Scoped, Singleton and HostedService
C#CC# / help
3y ago
Cookies and JWT for Authentication
C#CC# / help
11mo ago