Kai G Kai G - 28 days ago 16
ASP.NET (C#) Question

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?

Answer

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.