Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 401
xport Avatar asked Jan 22 '26 12:01

xport


1 Answers

You can access it by using another overload of ConfigureServices:

Host.CreateDefaultBuilder(args)
    .ConfigureServices((context, services) =>
    {
        var config = context.Configuration;
    });
like image 59
juunas Avatar answered Jan 25 '26 02:01

juunas



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!