Home > Software engineering >  How to get IConfiguration for AddSingleton?
How to get IConfiguration for AddSingleton?

Time:10-08

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?
});

CodePudding user response:

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();

CodePudding user response:

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);
  • Related