I want a simple static class that accesses the Configuration object. All the config info is already read in from the appsettings.json file in the Startup class. I just need an easy way to access it. Is this possible?
namespace MyNamespace
{
public static class Config
{
public string Username => Configuration["Username"];
public string Password => Configuration["Password"];
}
}
Anywhere else in the app:
string username = Config.Username;
string password = Config.Password;
The IConfiguration is Injectable anywhere within the Project. But in the case of static class, the option I am using and maybe only approach...
var Configuration = new ConfigurationBuilder() .AddUserSecrets<Startup>() .Build();
And, you can add required section, such in this code block above, I added 'UserSecrets'.Try avoid using a static class and use DI
The setup DI in StartUp class
And use it like so
This has already been said but I'm going to say it.
Static classes are not a best practice of Object Oriented Programming. I think for this reason, .Net Core provides us with a way to get values through Dependency Inject. This is what I've noticed from my research but I am also speculating a bit. As developers, we need to follow this paradigm shift in order to use .Net Core well.
The Options Pattern is a good alternative to the static config. In your case, it'll look like this:
appsettings.json
SystemUser.cs
Startup.cs
And to use the SystemUser class, we do the following.
TestController.cs
Even though we are not using a static class, I think this is the best alternative that fits your needs. Otherwise, you might have to use a static property inside the Startup class which is a scary solution imo.
After much research, this works (in ASPNetCore 2.2) for accessing the appsettings.json config from a static class but for some reason appsettings.development.json no longer loads properly but it might be something else in my project messing that up. The reloadOnChange does work. As a bonus it also has IHostingEnvironment and IHttpContextAccessor. While this works, I have recently decided to switch back to a more DI approach to follow the paradigm shift as others have mentioned.
So here is one of many ways to access some DI stuff (including the configuration) in a static class:
AppServicesHelper.cs:
Startup.cs:
Controller:
Another class library:
MyAppSettings.cs is any class that maps to a MyAppSettings section in appsettings.json:
appsettings.json:
I think you could use extension function, something like this
Then any place , just injection IConfiguration and use extension method
Consider using the instructions here for ASP.NET Core Configuration.
You can create a class to store your configuration settings and then access the values, something like this:
In Startup - ConfigureServices:
Then just inject your object wherever you need as: