In a previous article, we gave a detailed introduction to configuration configuration in .NET, and explained the core interfaces and main implementation classes in the configuration from the entire source code. The article link is:/home/detail/1912874623360438272. In this article, we will mainly introduce how each configuration is used.
Memory-based configuration program
The memory-based configuration program mainly maintains a Key-Value key-value pair in memory.
static void MemoryConfig()
{
List<KeyValuePair<string, string?>>? initialData = new List<KeyValuePair<string, string?>>();
(new KeyValuePair<string, string?>("name", "tom"));
IConfigurationRoot configuration = new ConfigurationBuilder()
.AddInMemoryCollection(initialData)
.Build();
("name:" + configuration["name"]);
}
The call is as follows:
static void Main(string[] args)
{
MemoryConfig();
}
Based on existing configuration providers
This configuration provider is used relatively little, and is a configuration provider implemented by Microsoft in the class library by default. It can use existing configurationsIConfigurationRoot
Encapsulated as a configuration provider. If you need to quickly copy a new configuration for existing configurations, you can use this configuration provider.
static void ChainedConfig()
{
List<KeyValuePair<string, string?>>? initialData = new List<KeyValuePair<string, string?>>();
(new KeyValuePair<string, string?>("name", "tom"));
//Initialize an existing configuration
IConfigurationRoot configuration = new ConfigurationBuilder()
.AddInMemoryCollection(initialData)
.Build();
//Based on the existing configuration, regenerate an identical configuration.
IConfigurationRoot newConfiguration = new ConfigurationBuilder()
.AddConfiguration(configuration)
.Build();
("name:" + configuration["name"]);
}
Command line-based configuration provider
A command line-based configuration program can obtain configuration from the console's command line. This configuration provider can quickly decompose command line parameters into Key-Value key-value pairs. Instead of manually processing the strings ourselves (usually we will split them into arrays according to spaces, and then obtain keys and values according to equal signs)
//Command line-based configuration
static void CommandLineConfig()
{
IConfigurationRoot configuration = new ConfigurationBuilder()
.AddCommandLine(["name=tom","age=32"])
.Build();
("name:" + configuration["name"]);
Environment variable-based configuration provider
.NET can read Key-Value key-value pairs in environment variables and can filter to specified prefixes for filtering. In the following code, the program will load all variables starting with TEST_ in the environment variable into the configuration. We will add a TEST_Name variable to the system variable. We must restart the computer, otherwise the added environment variable will not take effect. Our program can then read the variable value of TEST_Name
static void EnvironmentConfig()
{
IConfigurationRoot configuration = new ConfigurationBuilder()
.AddEnvironmentVariables("Test_")
.Build();
("name:" + configuration["Name"]);
}
Json file-based configuration provider
JSON-based configuration files are our most commonly used configuration file format. .NET provides a standard json configuration provider. We use the code to load the configuration from a file and when it is modified, the configuration in the program will also be updated.
//Configuration based on Json file
static void AddJsonFileConfig()
{
IConfiguration configuration = new ConfigurationBuilder()
.AddJsonFile("", optional: true, reloadOnChange: true)
.Build();
("name:" + configuration["name"]);
}
The configuration file contents are as follows:
{
"person":
{
"name":"caoripeng",
"age":12,
"school":"Peking University"
},
"name":"tom11"
}
XML file-based configuration provider
XML-based configuration files are also our most commonly used configuration file format. .NET provides a standard XML configuration provider. We use the code to load the configuration from a file and when it is modified, the configuration in the program will also be updated.
//Configuration based on XML file
static void AddXmlFileConfig()
{
IConfiguration configuration = new ConfigurationBuilder()
.AddXmlFile("", optional: true, reloadOnChange: true)
.Build();
("name:" + configuration["name"]);
}
The configuration file contents are as follows:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<config>
<name>tom</name>
<age>21</age>
<school>beijing</school>
</config>
Ini file-based configuration provider
We usually use Ini configuration files, but Microsoft still provides us with a configuration provider based on Ini files.
//Configuration based on INI file
static void AddIniFileConfig()
{
IConfiguration configuration = new ConfigurationBuilder()
.AddIniFile("", optional: true, reloadOnChange: true)
.Build();
("name:" + configuration["person:name"]);
}
The contents of the file are as follows:
[person]
name=tom
age=27
Custom configuration provider
The configuration provider provided by the official can basically meet most of our needs, but if our configuration is stored in the registry and in the database, the official configuration provider cannot meet our requirements at this time, and we need to customize the configuration provider. Custom configuration providers are simple, mainly including two classes: custom configuration sourceIConfigurationSource
, custom configuration providerConfigurationProvider
and an extension method for the current configuration. In the following code, we simulate a database-based configuration provider that is responsible for reading configuration from the database's configuration table Config table. Of course, we are not really reading the database tables, we can improve the code by ourselves.
//Custom configuration source
public class DataBaseConfigurationSource: IConfigurationSource
{
public IConfigurationProvider Build(IConfigurationBuilder builder)
{
return new DataBaseConfigurationProvider();
}
}
//Custom configuration provider
public class DataBaseConfigurationProvider: ConfigurationProvider
{
public override void Load()
{
();
//Read the database configuration
}
}
//Extended method of database configuration program
public static class DataBaseConfigurationExtensions
{
public static IConfigurationBuilder AddDb(this IConfigurationBuilder configurationBuilder)
{
(new DataBaseConfigurationSource());
return configurationBuilder;
}
}
//Call case
static void Main(string[] args)
{
var builder = new ConfigurationBuilder()
.AddDb()
.Build();
var value = builder["key"];
}