. Net Core configuration and automatic update,. netcore automatic update
. 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.
| 12345 |
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:
| 12 |
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.
| 1 |
services.Configure<DatabaseOption>(configuration.GetSection("Database")); |
And then inject it into the constructor.
?
| 1234 |
public EntityFrameWorkConfigure(IOptions<DatabaseOption> dataBaseOption) { _dataBaseOption = dataBaseOption; } |
Note: IOptions <T> is a singleton. That is, when you modify the value of etettings. json, it will not change. Therefore, 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>
| 1234 |
public EntityFrameWorkConfigure(IOptionsSnapshot<DatabaseOption> dataBaseOption) { _dataBaseOption = dataBaseOption; } |
Address: http://www.zkea.net/codesnippet/detail/post-80
. NET community news, deep good article, welcome to visit the public number article summary http://www.csharpkit.com