'Why is static Configuration.GetSection() not available?

In my ASP.NET Core 3.1 project I am trying to read a configuration option from "appsettings.json" via dependency injection service container just as explained by the docs or also by this SO answer.

But whenever I come to the point where I need to add Configuration.GetSection to ConfigureServices() in "Startup.cs", I am getting error:

CS0120  An object reference is required for the non-static field, method, or property 'Configuration.GetSection(string)'

enter image description here

static Configuration.GetSection is part of ".NET Platform extensions 3.1". Do I need to install a dependency/add an assembly?

I already tried installing NuGet ConfigurationManager.



Solution 1:[1]

Those examples from MS site do not call GetSection as static method:

public class Test21Model : PageModel
{
    private readonly IConfiguration Configuration;
    public PositionOptions positionOptions { get; private set; }

    public Test21Model(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public ContentResult OnGet()
    {            
        positionOptions = Configuration.GetSection(PositionOptions.Position)
                                                     .Get<PositionOptions>();

        return Content($"Title: {positionOptions.Title} \n" +
                       $"Name: {positionOptions.Name}");
    }
}

So you need to define class property Configuration and instantiate it in the constructor, as in the example - and then call that method on instance of the class.

Solution 2:[2]

in Program.cs

change:

builder.Services.Configure(Configuration.GetSection("MailSettings"));

to:

builder.Services.Configure(builder.Configuration.GetSection("MailSettings"));

Solution 3:[3]

Thanks to Panagiotis and kosist, I found out that the question boils down to "How to access Configuration in startup?"

The answer is in the comments ("injected by the DI") and as code in the docs:

public class Startup
{
    public IConfiguration Configuration { get; }

    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<PositionOptions>(Configuration.GetSection(PositionOptions.Position));
    }
}

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 Jack Miller
Solution 2 Alfi
Solution 3 Jack Miller