'How to access IConfiguration provided by CreateDefaultBuilder() from within ConfigureServices()?

I usually do the following

static void Main()
{
    IConfiguration config = new ConfigurationBuilder()
                        .SetBasePath(Directory.GetCurrentDirectory())
                        .AddJsonFile("appsettings.json", false, true)
                        .Build();

    Host.CreateDefaultBuilder()
        .ConfigureServices(isc =>
        {
            isc.AddSingleton(config);

            isc.AddDbContext<DbContext>(options =>
            {
                options.UseSqlServer(config.GetConnectionString("Duplicate"));
            });
        })                
        .Build();
}

I just knew that configuration for appsettings.json is already provided by CreateDefaultBuilder() so I think I should be able to simplify my code as follows.

static void Main()
{
    Host.CreateDefaultBuilder()
        .ConfigureServices(isc =>
        {
            isc.AddDbContext<DbContext>(options =>
            {
                options.UseSqlServer(********.GetConnectionString("Duplicate"));
            });
        })                
        .Build();
}

Question

How to obtain the configuration ******** provided by default?



Solution 1:[1]

You can access it by using another overload of ConfigureServices:

Host.CreateDefaultBuilder(args)
    .ConfigureServices((context, services) =>
    {
        var config = context.Configuration;
    });

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 juunas