Reputation: 7657
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)'
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.
Upvotes: 3
Views: 1889
Reputation: 167
in Program.cs
change:
builder.Services.Configure(Configuration.GetSection("MailSettings"));
to:
builder.Services.Configure(builder.Configuration.GetSection("MailSettings"));
Upvotes: 8
Reputation: 3057
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.
Upvotes: 3
Reputation: 7657
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));
}
}
Upvotes: 0