简体   繁体   中英

ASP.Net Core injecting setting

In ASP.Net Core it's possible to inject config values into a class using IOptions<T> .

So if I have the following appsettings.json config:

{
  "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.

How can I inject the RootUrl setting into my constructor or is this not supported?

Create a class as below

public class AppSettings {
    public string RootUrl{ get; set; }
}

Inject it into your startup.cs as below.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM