. Net Core configuration and automatic update Implementation Method,. netcore
. Net Core migrates the configuration in Web. Config to the appsettings. json file, and uses ConfigurationBuilder to read the configuration file. You can also set Automatic reload after the configuration file changes, so that you do not need 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();
Read configuration information
Configuration reading is much more convenient than before and can be used directly. After the ConfigurationBuilder calls the Build () method, you can directly set the value:
Configuration = builder.Build();var value = Configuration["Section:Key"]
After the Configuration is updated, use Configuration ["Section: Key"] to obtain the latest value.
Configure a strong type
You can directly use a strong type to convert the configuration file to your object for direct use, as long as the object attributes correspond to the configuration.
services.Configure<DatabaseOption>(configuration.GetSection("Database"));
And then inject it into the constructor.
public EntityFrameWorkConfigure(IOptions<DatabaseOption> dataBaseOption){_dataBaseOption = dataBaseOption;}
Note:IOptions <T> is a singleton. That is, when you modify the value of etettings. json, you must restart your program to update it.
Use IOptionsSnapshot <T> to automatically update
If you want to use a strong type, you can automatically update your configuration without restarting the program. You can use IOptionsSnapshot <T>
public EntityFrameWorkConfigure(IOptionsSnapshot<DatabaseOption> dataBaseOption){_dataBaseOption = dataBaseOption;}
The above. Net Core configuration and automatic update Implementation Method is all the content that I have shared with you. I hope to give you a reference and support for the customer's house.