Recently, I was working on a project with ASP. NET Core and encountered a problem reading the configuration file in a class that cannot use injection.
We all know that it is recommended to use injection to read the configuration file in the core, so that the read value is strongly typed, which makes up the flaw of Web. config.
When I used to have a good time to meet a static class also need to read the configuration file problems, tangled up for a few days before this blog post.
The original version looks like this.
Public Static classconfigurationmanager{Staticiconfiguration Configuration; StaticConfigurationManager () {varBuilder =NewConfigurationbuilder (). Setbasepath (Directory.GetCurrentDirectory ()). Addjsonfile ("Appsettings.json", Optional:true, Reloadonchange:true) . Addenvironmentvariables (); Configuration=Builder. Build (); } Public Static stringGetValue (stringkey) { returnConfiguration[key]; } Public StaticT getvalue<t> (stringkey) { returnConfiguration.getvalue<t>(key); }}
The above code can only read the configuration in the configuration Appsettings.json, because our development environment has a lot of sets, this does not meet our needs
but this tool class is static and cannot inject environment variables, which is a problem that bothers me, finally with the help of the master of the solution, which is the following version
Public Static classconfigurationmanagerv2{Staticiconfiguration Configuration; StaticConfigurationManagerV2 () {
//Read environment variables here var provider = new environmentvariablesconfigurationprovider (); Provider. Load (); Provider. Tryget ("aspnetcore_environment", out string environmentname ); varBuilder =NewConfigurationbuilder (). Setbasepath (Directory.GetCurrentDirectory ()). Addjsonfile ("Appsettings.json", Optional:true, Reloadonchange:true) . Addjsonfile ($ "appsettings.{ Environmentname}.json", Optional: true, Reloadonchange: true ) . Addenvironmentvariables (); Configuration=Builder. Build (); } /// <summary> /// /// </summary> /// <param name= "key" > Case insensitive</param> /// <returns></returns> Public Static stringGetValue (stringkey) { returnConfiguration[key]; } Public StaticT getvalue<t> (stringkey) { returnConfiguration.getvalue<t>(key); }}
This allows us to use the configuration file in a static file, and can read different configuration files based on the environment variables.
Done!
ASP. NET Core reads a configuration file without using an injection method