The editor below will share with you an article on the implementation method of .Net Core configuration and automatic update. It has a good reference value and I hope it will be helpful to everyone in learning .NET. Friends who are interested in .NET, please follow the editor to take a look.
.Net Core migrated the configuration in the previous Web.Config to the appsettings.json file, and used ConfigurationBuilder to read thisConfiguration file. And you can set it to automatically reload after the configuration file changes, so you don't 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 reading
Configuration reading It is much more convenient to take than before and you can use it directly. After the ConfigurationBuilder calls the Build() method, you can directly get the value:
Configuration = builder.Build(); var value = Configuration["Section:Key"]
When the configuration is updated, use Configuration["Section :Key"] also gets the latest value.
Configuring strong typing
You can use strong typing directly and convert the configuration file into your objectUse it directly, As long as the properties of the object correspond one-to-one with the configuration.
services.Configure<DatabaseOption>(configuration.GetSection("Database"));
Then inject ## in the constructor
#
public EntityFrameWorkConfigure(IOptions<DatabaseOption> dataBaseOption) { _dataBaseOption = dataBaseOption; }
##Note: IOptions
If you want to automatically update your configuration without restarting the program when using strong typing, You can use IOptionsSnapshot
public EntityFrameWorkConfigure(IOptionsSnapshot<DatabaseOption> dataBaseOption) { _dataBaseOption = dataBaseOption; }
The above .Net Core configuration and automatic update implementation method is shared by the editor This is all your content, I hope it can give you a reference, and I hope you will support the PHP Chinese website.
Related recommendations:
How to use EF Core to migrate the database to SQL Server in the .NET Core class library _Practical Tips
Solutions to common problems in deploying asp.net to IIS_Practical TipsASP.NET Core Class Library Detailed explanation of how to read configuration files in the projectThe above is the detailed content of How to implement .Net Core configuration and automatic updates_Practical tips. For more information, please follow other related articles on the PHP Chinese website!