[英]ASP.Net Core injecting setting
In ASP.Net Core it's possible to inject config values into a class using IOptions<T>
. 在ASP.Net Core中,可以使用
IOptions<T>
将配置值注入类中。
So if I have the following appsettings.json
config: 所以,如果我有以下
appsettings.json
配置:
{
"CustomSection": {
"Foo": "Bar"
},
"RootUrl": "http://localhost:12345/"
}
I can inject IOptions<CustomSection>
into my constructor (assuming I've defined a CustomSection
class) and read the Foo
property. 我可以将
IOptions<CustomSection>
注入到我的构造函数中(假设我已经定义了一个CustomSection
类)并读取了Foo
属性。
How can I inject the RootUrl
setting into my constructor or is this not supported? 如何将
RootUrl
设置注入构造函数或不支持?
Create a class as below 创建一个类,如下所示
public class AppSettings {
public string RootUrl{ get; set; }
}
Inject it into your startup.cs as below. 将其注入您的startup.cs,如下所示。
public void ConfigureServices(IServiceCollection services)
{
services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
}
And use it in your controller as below. 并在控制器中使用它,如下所示。
public CustomerController(IOptions<AppSettings> appSettings)
{
[variable] = appSettings.Value;
}
Let me know if this works for you. 如果这对您有用,请告诉我。
From the docs Using options and configuration objects that is not possible : 从文档中使用 不可能的 选项和配置对象 :
The options pattern enables using custom options classes to represent a group of related settings.
选项模式允许使用自定义选项类来表示一组相关设置。 A class needs to have a public read-write property for each setting and a constructor that does not take any parameters (eg a default constructor) in order to be used as an options class.
类需要为每个设置都有一个公共读写属性,以及一个不带任何参数的构造函数(例如默认构造函数)才能用作选项类。
That means you need to generate a class to read it's configuration value(s). 这意味着您需要生成一个类来读取它的配置值。 But in your sample
RootUrl
cannot be constructed via a class. 但是在你的示例中,
RootUrl
不能通过类构造。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.