I have an issue related to dependency injection in the Program.cs of a .Net 7 application.
In this case it's an API, but that does not really matter.
Before calling the line:
var app = builder.Build();
I am adding a few singletons normally with :
My issue is that the HTTP client singleton requires info from the config singleton, and it's not a simple case of injecting the former into the latter.
We can't use appsettings.json to manage our configuration, that would be too easy, and because the second one is an HTTP client, I have this code :
builder.Services.AddHttpClient<IMyHttpClient, MyHttpClient>(client =>
client.BaseAddress = new Uri(myConfig.myURI);
return new HttpClientHandler()
UseDefaultCredentials = true
.. all this still before I call builder.Build();
I have already googled and chatGPT'd the problem, but the solutions I get are for .Net 6 at best, and do not apply.
My current solution is to use builder.Services.BuildServiceProvider().GetService<imyconfig>() to get an instance of myConfig, but then the builder is called twice, so this instance is lost, and after the builder.Build(), I have to read my config again.
Technically, this works, but it's ugly and triggers my OCD.
If there's any DI god out there, what am I missing ?
Thanks in advance
modified 28-Apr-23 9:43am.