0

so I use .net FW 6.0 minimap API and add a few services and configurations like this:

var builder = WebApplication.CreateBuilder();
builder.Configuration.AddJsonFile("appsettings.json");
builder.Services.AddTransient<IDockerService, DockerService>();
var app = builder.Build();
...

So now I want to add a singleton to my service collection BUT when it resolved I want to insert a configuration item - to do that I need to have access to the configuration, but because it is not build at the time I register it, I can't access it, so I am stuck in a loop:

builder.Services.AddSingleton<MyService>((provider) => 
{  
   // Read a value out of configuration here, but how?
});
PassionateDeveloper
  • 14,558
  • 34
  • 107
  • 176

2 Answers2

2

Not sure if I understood the question correctly, but why not use the builder.Configuration there.

var builder = WebApplication.CreateBuilder();
builder.Configuration.AddJsonFile("appsettings.json");

builder.Services.AddTransient<IDockerService, DockerService>();

builder.Services.AddSingleton<MyService>((provider) => 
{  
   // Read a value out of configuration here, but how?
   builder.Configuration["Key"]
});

var app = builder.Build();
WisdomSeeker
  • 854
  • 6
  • 8
  • because builder.Configuration is not an IConfiguration - you can't access it here. It's an IConfigurationBuilder, which has no access, until the Build() Method is done. – PassionateDeveloper Oct 07 '22 at 12:01
  • Hmm. I have used it like so in .Net 6 projects and it worked. Maybe some gap in understanding the question. – WisdomSeeker Oct 07 '22 at 13:20
  • 1
    Could be mistaken but I think @WisdomSeeker is correct. `builder.Configuration` in .NET 6 now exposes the Configuration before `builder.Build()` gets called. I found a similar post that might explain it better: [access-configuration-during-startup](https://stackoverflow.com/questions/69722872/asp-net-core-6-how-to-access-configuration-during-startup). In addition to the `["key"]` you can also use `GetSection("Key")` – ProdigalTechie Oct 08 '22 at 00:53
1

The only other things that I can think of would be to pass builder.Configuration to your MyService class:

public static IServiceCollection AddMyServices(this IServiceCollection services, IConfiguration config)
{
   
   services.AddSingleton<MyService>((provider) => {
      // set your value here from config
   });

}

And in your Program.cs file:

builder.Services.AddMyServices(builder.Configuration);
ProdigalTechie
  • 188
  • 1
  • 8