Back to Catalog
The Ancients Cloud "one mountain does not allow two Tigers", and after the dotnet core era, we can see some of the official demo, it will be the data connection string and other configuration items are directly hardcoded in the code, that is, in the startup definition, ask you in the production environment how compatible! Of course, you would say, can be configured in the corresponding appsettings, said it is the corresponding appsettings, because the dotnet core configuration file has an environmental distinction, generally use the following name to represent different environments:
- Development environment, development
- Pre-release environment, Staging
- Production environment, Production
For both, how to choose the configuration file and hard-coded configuration, and if both are set, then who should be? The uncle thinks, if both are set, that is the configuration file, when the configuration file is not defined, and then the hard-coded configuration, which is their priority, because of the following points:
- Hard coding facilitates debugging in the development environment
- After you specify a running environment, the configuration file chooses a different configuration depending on the environment
- Optimization level, configuration file is better than hard coding
The following is the warehousing service at the time of registration, select the configuration of the policy, of course, you can make this logic a decoration, feel better.
Public classefoptionsextension:ilindoptionsextension {Private ReadOnlyAction<repositoryoptions>_configure; PublicEfoptionsextension (action<repositoryoptions>Configure) {_configure=Configure; } Public voidaddservices (iservicecollection services) {varOptions =Newefoptions (); _configure?. Invoke (options);//Decoration if(oconfigfilehelper.get<efoptions>(). ConnString!=NULL)//configuration file first hard-coded{options. ConnString= configfilehelper.get<efoptions>(). connstring; } if(configfilehelper.get<efoptions>(). DbType!=dbtype.none) {options. DbType= configfilehelper.get<efoptions>(). DbType; } services. Addsingleton<ilogger, filelogger> ();//LogServices. Addsingleton (options);//EF ConfigurationServices. AddTransient (typeof(DbContext), options. Dbcontexttype);//Registering data contexts, instance patternsServices. AddTransient (typeof(irepository<>),typeof(efrepository<>));//Register Data Warehousing } }
After we have published, the general release of Dotnet core to Linux or directly in the Docker container to run, just set the corresponding environment variables can be very convenient!
ENV aspnetcore_environment="Production"
Once setup is complete, dotnet Core chooses the corresponding appsettings. Production.json file to load!
Thank you for reading!
Back to Catalog
How Dotnetcore Cross-platform ~ configuration files and configuration code coexist