Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

.net Core how to configure Configuration

2025-03-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces ".net Core how to configure Configuration". In daily operation, I believe many people have doubts about how to configure Configuration with .net Core. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts about ".net Core how to configure Configuration". Next, please follow the editor to study!

Catalogue

Core class

Construction

ConfigurationBuilder

IConfigurationSource

ConfigurationProvider

ConfigurationRoot

Query

Indexer

GetSection

DBConfiguration example

Recently, I have studied the source code implementation of the .NetCore configuration option and learned a lot. This article will first write about the learning achievements of IConfiguration, which will be added at the end of Options.

Core class

ConfigurationBuilder:IConfigurationBuilder (build IConfiguration)

IConfigurationSource (configuration data source)

IConfigurationProvider (changes the original structure of the configuration source to IDictionary)

ConfigurationRoot:IConfigurationRoot:IConfiguration (configure root node)

Build ConfigurationBuilder

Here is the main code in ConfigurationBuilder

You can see that the main function of ConfigurationBuilder is to configure data sources into the collection

Call the Build function of IConfigurationSource in turn when Build, and add the returned IConfigurationProvider to the List

Finally, a ConfigurationRoot object is built with the collection of IConfigurationProvider.

Public IList Sources = new List (); public IConfigurationBuilder Add (IConfigurationSource source) {Sources.Add (source); return this;} public IConfigurationRoot Build () {List list = new List (); foreach (IConfigurationSource source in Sources) {IConfigurationProvider item = source.Build (this); list.Add (item);} return new ConfigurationRoot (list);} IConfigurationSource

Public class EnvironmentVariablesConfigurationSource: IConfigurationSource {public string Prefix; public IConfigurationProvider Build (IConfigurationBuilder builder) {return new EnvironmentVariablesConfigurationProvider (Prefix);} public EnvironmentVariablesConfigurationSource () {}} public class CommandLineConfigurationSource: IConfigurationSource {public IDictionary SwitchMappings; public IEnumerable Args; public IConfigurationProvider Build (IConfigurationBuilder builder) {return new CommandLineConfigurationProvider (Args, SwitchMappings) } public CommandLineConfigurationSource () {}} / / JsonConfigurationSource inherits from FileConfigurationSource, which I combine into one public abstract class JsonConfigurationSource: IConfigurationSource {public IFileProvider FileProvider {get; set;} public string Path {get; set;} public bool Optional {get; set;} public bool ReloadOnChange {get; set;} public int ReloadDelay {get; set;} = 250; public Action OnLoadException {get; set;} public IConfigurationProvider Build (IConfigurationBuilder builder) {FileProvider = FileProvider?? Builder.GetFileProvider (); OnLoadException = OnLoadException? Builder.GetFileLoadExceptionHandler (); return new JsonConfigurationProvider (this);} public void ResolveFileProvider () {if (FileProvider = = null & &! string.IsNullOrEmpty (Path) & & System.IO.Path.IsPathRooted (Path)) {string directoryName = System.IO.Path.GetDirectoryName (Path); string text = System.IO.Path.GetFileName (Path) While (! string.IsNullOrEmpty (directoryName) & &! Directory.Exists (directoryName)) {text = System.IO.Path.Combine (System.IO.Path.GetFileName (directoryName), text); directoryName = System.IO.Path.GetDirectoryName (directoryName);} if (Directory.Exists (directoryName)) {FileProvider = new PhysicalFileProvider (directoryName); Path = text;}

Above shows the more commonly used three kinds of ConfigurationSource, the code is relatively simple.

It is also easy to see that the role of ConfigurationSource is to configure the data source and not to parse the data.

The function of parsing the data source is completed by IConfigurationProvider

ConfigurationProvider

The following five functions are defined for the IConfigurationProvider interface

Public interface IConfigurationProvider {bool TryGet (string key, out string value); void Set (string key, string value); IChangeToken GetReloadToken (); void Load (); IEnumerable GetChildKeys (IEnumerable earlierKeys, string parentPath);}

ConfigurationProvider is an abstract class that inherits the IConfigurationProvider interface

When you create a new Provider, you usually choose to inherit ConfigurationProvider directly. Let's take a look at several core methods of ConfigurationProvider.

Public abstract class ConfigurationProvider: IConfigurationProvider {private ConfigurationReloadToken _ reloadToken = new ConfigurationReloadToken (); protected IDictionary Data= new Dictionary (StringComparer.OrdinalIgnoreCase); public virtual bool TryGet (string key, out string value) = > Data.TryGetValue (key, out value); public virtual void Set (string key, string value) = > Data [key] = value; public virtual void Load () {} public IChangeToken GetReloadToken () {return _ reloadToken;} protected void OnReload () {ConfigurationReloadToken configurationReloadToken = Interlocked.Exchange (ref _ reloadToken, new ConfigurationReloadToken (); configurationReloadToken.OnReload ();}

It can be inferred:

The Load function is responsible for reading data from the source data and then assigning values to the dictionary Data

ConfigurationProvider stores data in the dictionary Data, and adding modifications is an operation on the dictionary.

Each ConfigurationProvider generates an IChangeToken, generates a new Token when the OnReload function is called, and calls the OnReload function of the original Token

ConfigurationRoot

In ConfigurationBuilder's Build function, we generate a ConfigurationRoot and pass him all the ConfigrationProvider lists. Let's see what he has done with our Provider.

Private ConfigurationReloadToken _ changeToken = new ConfigurationReloadToken (); public ConfigurationRoot (IList providers) {_ providers = providers; _ changeTokenRegistrations = new List (providers.Count); foreach (IConfigurationProvider p in providers) {p.Load (); ChangeToken.OnChange (p.GetReloadToken, delegate {var oldToken=Interlocked.Exchange (ref _ changeToken, new ConfigurationReloadToken ()); oldToken.OnReload () })}} public IChangeToken GetReloadToken () = > _ changeToken

The above code also simplifies some places. You can see that ConfigurationRoot did two main things when it was generated.

1. Call the Load function of Provider, which assigns a value to the Data of Provider

two。 Read the ReloadToken of Provider. The Reload event of each Provider triggers the Reload event of ConfigurationRoot's own ReloadToken.

At this point, the configuration of the data source construction is finished!

Query

There are two basic ways to configure regular queries: indexer and GetSection (string key)

The rest of GetValue and so on are some extension methods, which are not studied in this article.

Indexer

The indexer's query is executed by flashback querying all the Provider, then calling the TryGet function of Provider, renaming the Key when querying, and the final addition will take effect.

The assignment is to call the Set function of each Provider in turn.

Public string this [string key] {get {for (int num = _ providers.Count-1; num > = 0; num--) {if (_ providers[ num] .TryGet (key, out var value)) {return value;}} return null;} set {foreach (IConfigurationProvider provider in _ providers) {provider.Set (key, value);}} GetSection

Public IConfigurationSection GetSection (string key) {return new ConfigurationSection (this, key);} public class ConfigurationSection: IConfigurationSection, IConfiguration {private readonly IConfigurationRoot _ root; private readonly string _ path; private string _ key; public string Value {get {return _ root [path];} set {_ root [path] = value;}} / / ConfigurationPath.Combine = string.Join (":", paramList); public string this [string key] {get {return _ root [ConfigurationPath.Combine (Path, key)] } set {_ root [ConfigurationPath.Combine (Path, key)] = value;}} public ConfigurationSection (IConfigurationRoot root, string path) {_ root = root; _ path = path;} public IConfigurationSection GetSection (string key) {return _ root.GetSection (ConfigurationPath.Combine (Path, key));} public IEnumerable GetChildren () {return _ root.GetChildrenImplementation (Path);} public IChangeToken GetReloadToken () {return _ root.GetReloadToken ();}}

You can see that GetSection generates a ConfigurationSection object

When ConfigurationSection reads / sets the value, it actually uses: concatenate the Key of the query, and then calls the assignment or query function of IConfigurationRoot (_ root).

These are probably the knowledge points about the configuration and reading of Configuration, and there are more in-depth discussions on the binding of objects, such as Get Bind GetChildren (), etc., which is more difficult to read. You need to read it line by line of code, and you may have time to study it again later.

Finally, a small example of loading configuration sources from data and updating them dynamically is posted.

DBConfiguration example

Public void Run () {var builder = new ConfigurationBuilder (); var dataProvider = new DBDataProvider (); builder.Sources.Add (new DBConfigurationSource () {DataProvider = dataProvider, ReloadOnChange = true, Table = "config"}); IConfigurationRoot config = builder.Build (); Console.WriteLine (config ["time"]) Task.Run (() = > {while (true) {Thread.Sleep (2000); dataProvider.Update ("config"); Console.WriteLine ($"read configuration time: {config [" time "]}")) }}); Thread.Sleep (20000);} public class DBConfigurationProvider: ConfigurationProvider {private DBConfigurationSource Source {get;} public DBConfigurationProvider (DBConfigurationSource source) {Source = source;} public override void Load () {if (Source.ReloadOnChange) {ChangeToken.OnChange (() = > Source.DataProvider.Watch (Source.Table), LoadData) } LoadData ();} private void LoadData () {var data = Source.DataProvider.GetData (Source.Table); Load (data); OnReload ();} public void Load (Dictionary data) {var dic = new SortedDictionary (StringComparer.OrdinalIgnoreCase); foreach (var element in data) {dic.Add (element.Key, element.Value?.ToString ()) } base.Data = dic;} public class DBConfigurationSource: IConfigurationSource {public DBDataProvider DataProvider {get; set;} public string Table {get; set;} public bool ReloadOnChange {get; set;} public bool Optional {get; set;} public DBConfigurationSource () {} public IConfigurationProvider Build (IConfigurationBuilder builder) {return new DBConfigurationProvider (this);} public class DBDataProvider {private ConcurrentDictionary tableToken = new ConcurrentDictionary () Public DBDataProvider () {} public Dictionary GetData (string table) {switch (table) {case "config": return GetConfig ();} return new Dictionary ();} public void Update (string table) {Console.WriteLine ($"Update database data table: {table}") If (tableToken.TryGetValue (table, out CancellationTokenSource cts)) {var oldCts = cts; tableToken [table] = new CancellationTokenSource (); oldCts.Cancel ();} private Dictionary GetConfig () {var valueDic = new Dictionary (); valueDic.TryAdd ("time", DateTime.Now.ToString ()); valueDic.TryAdd ("weather", "windy") ValueDic.TryAdd ("people_number:male", 100); valueDic.TryAdd ("people_number:female", 150); return valueDic;} public IChangeToken Watch (string table) {var cts = tableToken.GetOrAdd (table, x = > new CancellationTokenSource ()); return new CancellationChangeToken (cts.Token) }} at this point, the study on "how to configure Configuration with .net Core" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report