[英]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 .在我的 ASP.NET Core 3.1 项目中,我正在尝试通过依赖注入服务容器从“appsettings.json”读取配置选项,正如文档或此 SO 答案所解释的那样。
But whenever I come to the point where I need to add Configuration.GetSection
to ConfigureServices()
in "Startup.cs", I am getting error:但是每当我需要将
Configuration.GetSection
添加到“Startup.cs”中的ConfigureServices()
时,我都会收到错误消息:
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". static Configuration.GetSection
是“.NET 平台扩展 3.1”的一部分。 Do I need to install a dependency/add an assembly?我需要安装依赖项/添加程序集吗?
I already tried installing NuGet ConfigurationManager .我已经尝试安装NuGet ConfigurationManager 。
in Program.cs在 Program.cs 中
change:改变:
builder.Services.Configure(Configuration.GetSection("MailSettings"));
builder.Services.Configure(Configuration.GetSection("MailSettings"));
to:到:
builder.Services.Configure(builder.Configuration.GetSection("MailSettings"));
builder.Services.Configure(builder.Configuration.GetSection("MailSettings"));
Those examples from MS site do not call GetSection
as static method:来自 MS 站点的那些示例不会将
GetSection
调用为静态方法:
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 instantiate your configuration in the constructor, as in the example - and then call that method on instance of the class.因此,您需要在构造函数中实例化您的配置,如示例中所示 - 然后在类的实例上调用该方法。
Thanks to Panagiotis and kosist , I found out that the question boils down to " How to access Configuration
in startup? "感谢Panagiotis和kosist ,我发现问题归结为“如何在启动时访问
Configuration
? ”
The answer is in the comments ("injected by the DI") and as code in the docs :答案在评论中(“由 DI 注入”)和文档中的代码:
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));
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.