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;
Personally I like the method used in this link
Essentially it just adding a static field to your options class.
Then in any static class you can do:
Simple and very straight forward
If you are using environment variables as your configuration, you can access the environment variable directly rather than via the configuration object.
Here is a way to obtain the configuration values from a NET.Core page without having to reference these statically but then still being able to pass them to other static functions called from the non-static class.
At the top of your non-static class add this:
private readonly IConfiguration _configuration;
Then in the constructor function bring in the existing configuration as input to the function:
IConfiguration configuration
Then assign the configuration to your read only variable inside the constructor function:
_configuration = configuration;
Here is an example of what it should look like:
After this you can reference the configuration in any function in the class by referencing _configuration and can even then pass this on to other static functions that you call from other classes:
Then in the called static class I can make use of the configuration values:
I have a class that calls some stored procedures for viewing and amending data and passes parameter values from appsettings.json using this approach.
A slightly shorter version based on the same principle as above...
To use in another static class:
I agree with mcbowes, it's in the docs, but the first example looks more like what you need...want:
You can use Signleton pattern to access your configurations from anywhere
and in your startup class