The following small series for you to share a. Net core configuration and Automatic Update implementation method, has a good reference value, hope to learn from you. NET has helped. Take a look at the small partners who are interested in. Net.
. Net Core migrates the configuration in the previous web. config to the Appsettings.json file and uses Configurationbuilder to read the configuration file. And can be set after the configuration file changes, automatically reload, so that you do not have to restart your program.
var builder = new Configurationbuilder (). Setbasepath (env. Contentrootpath). Addjsonfile ("Appsettings.json", Optional:true, Reloadonchange:true). Addjsonfile ($ "appsettings.{ Env. Environmentname}.json ", optional:true). Addenvironmentvariables ();
Configuration information Read
The configured reads are much more convenient than before and are used directly. After Configurationbuilder calls the build () method, you can directly take the value:
Configuration = Builder. Build (); var value = configuration["Section:key"]
When the update is configured, the most recent value is obtained using configuration["Section:key".
Configure strongly typed
You can directly use a strong type to convert the configuration file to your object directly, as long as the object's properties correspond to one by one in the configuration.
Services. Configure<databaseoption> (configuration. GetSection ("Database"));
And then, in the constructor, inject the
Public entityframeworkconfigure (ioptions<databaseoption> databaseoption) {_databaseoption = DatabaseOption;}
Note: Ioptions<t> is a singleton, that is, when you modify the Appsettings.json, it does not change its value, so you must restart your program to update.
Automatic Updates with ioptionssnapshot<t>
If you want to use a strong type, you can also automatically update your configuration without restarting the program, you can use the ioptionssnapshot<t>
Public entityframeworkconfigure (ioptionssnapshot<databaseoption> databaseoption) {_dataBaseOption = DatabaseOption;}
The above-mentioned. Net core configuration and Automatic Update implementation method is the small part to share the whole content of everyone, I hope to give you a reference, but also hope that we support a lot of topic.alibabacloud.com.
Related recommendations:
How to migrate a database to SQL Server using EF Core in the. NET Core class Library Practical tips
Workaround for ASP. NET deployment to IIS FAQ _ Practical Tips
How to implement read configuration file in ASP. NET Core Class Library project