public class Bar
{
public static readonly string Foo = ConfigurationManager.AppSettings["Foo"];
}
In the .NET Framework 4.x, I can use the ConfigurationManager.AppSettings ["Foo"]
to get Foo
in Webconfig
,and then I can easily get the value of Foo
through Bar.Foo
But in .Net core, I mustto inject options
, And can not get the value of Foo
through Bar.Foo
Is there a method, which can be directly through the Bar.Foo
to get the value of Foo
?
The solutions on top are time consuming and not straightforward, this is the best effective way to do it, no setup needed on startup or anything. It's like using the good ol Configuration.Manager.AppSettings["setting"]
First create a class like "Credential":
Now that's setup let put the IConfiguration on your constructor like so:
Then you're ready to call it!
Assuming your appsettings.json looks like this:
Hope this helps somebody.
So there are really two ways to go about this.
Option 1 : Options Class
You have an appsettings.json file :
You create a Configuration POCO like so :
In your startup.cs you have something in your ConfigureServices that registers the configuration :
Then in your controller/service you inject in the IOptions and it's useable.
Personally I don't like using IOptions because I think it drags along some extra junk that I don't really want, but you can do cool things like hot swapping and stuff with it.
Option 2 : Configuration POCO
It's mostly the same but in your Configure Services method you instead bind to a singleton of your POCO.
And then you can just inject the POCO directly :
A little simplistic because you should probably use an interface to make unit testing a bit easier but you get the idea.
Mostly taken from here : http://dotnetcoretutorials.com/2016/12/26/custom-configuration-sections-asp-net-core/
You can also use the configuration directly. Your settings are injected so you can get to them with DI...
and then you can read your settings...
In this case I'm getting a collection back...