Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.Net Core - IConfigurationRoot read entire json file

I have following Config.jsonfile

{
   "UserId": 2930,
   "Phones":["<HomePhoneNumber>", "<MobileNumber>"]
}

And I have corresponding Config class in Config.cs

public class Config
{
  public int UserId { get; set; }
  public List<string> Phones { get; set;}
}

I was following this tutorial - https://keestalkstech.com/2018/04/dependency-injection-with-ioptions-in-console-apps-in-net-core-2/

But I don't have sections like his appsettings.json in my config.json file. I want to read that config file as a whole. How can I do that with ConfigurationBuilder?

class Program
{
    static async Task Main(string[] args)
    {
        var services = new ServiceCollection();
        ConfigureServices(services);
        var serviceProvider = services.BuildServiceProvider();

        var config = serviceProvider.GetService<Config>();
    }

    private static void ConfigureServices(IServiceCollection services)
    {
        services.AddLogging(builder => builder.AddDebug().AddConsole());

        var configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("Config.json", false)
            .Build();

        services.AddOptions();
        services.Configure<Config>(configuration);
    }
}
like image 601
Milan Avatar asked Jan 28 '26 21:01

Milan


1 Answers

Because of options configuration you would need to access it via IOptions

//...

var serviceProvider = services.BuildServiceProvider();
var option = serviceProvider.GetService<IOptions<Config>>();
var config = option.Value;

another approach would be to extract the class directly from configuration by binding to the desired object graph and then adding it to the service collection

//...

var configuration = new ConfigurationBuilder()
    .SetBasePath(Directory.GetCurrentDirectory())
    .AddJsonFile("Config.json", false)
    .Build();

var config = configuration.Get<Config>();
services.AddSingleton(config);

//...

With the above approach

//...

var config = serviceProvider.GetService<Config>();

will work as expected.

like image 153
Nkosi Avatar answered Jan 30 '26 10:01

Nkosi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!