Home > Enterprise >  How to access IConfiguration provided by CreateDefaultBuilder() from within ConfigureServices()?
How to access IConfiguration provided by CreateDefaultBuilder() from within ConfigureServices()?

Time:03-15

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?

CodePudding user response:

You can access it by using another overload of ConfigureServices:

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