3

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?

2

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

4 Comments

No that doesn't work because there is no section called 'AppSettings' in the config file.
@KaiG You can just use RootUrl, try it.
No, that throws an Exception when you try to use the setting because it can't parse the string into the expected format. I believe the accepted answer above is correct - it's not supported.
This would work find if you change to services.Configure<AppSettings>(Configuration);
3

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 (e.g. 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 RootUrlcannot be constructed via a class.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.