4.2 multi-level configuration (on) and 4.2 configuration change

Source: Internet
Author: User

4.2 multi-level configuration (on) and 4.2 configuration change

The configuration information is changeable and stored in the configuration file. developers can use the configuration file to change the application settings .. Net core provides multiple configuration methods, such as json file configuration, registry configuration, Environment configuration, and xml file configuration. A json configuration file is commonly used, that is, each application has a configuration file named etettings. json, which stores all the configuration information.

Here, I also need to note that the current system configuration is too large. I suggest using the Convention as much as possible, that is, the Convention is better than the configuration. For example, all MVC controllers end with a Controller, which is an example of better agreement than configuration.

However, this configuration method has the problem of repeated configuration. For example, if three application projects access a database, the database connection strings of the database will be stored in the configuration files of the three application projects respectively, when the database server address, user, password, and other changes, all need to be modified in these three projects. As the number of systems increases, it is easy to cause missed changes. Similarly, in the cloud environment, application projects can be deployed with dynamically allocated and scalable computing resources (multiple virtual servers). to modify a configuration item, you must modify the configuration files of each server at the same time, in the same way, it is easy to cause missed changes.

To solve this problem, we used a multi-level configuration file to extract the public configuration information and store it in an independent public configuration file, all three projects access the public configuration file to obtain the database connection string. Public configuration files can solve existing problems. However, a new problem was found during the actual operation, that is, a program exception was found during the operation. technicians often need to check the configuration information or modify the configuration, the customer's security requirements are relatively high (the customer's technical staff will not be able to speak out), and direct access to the server is not allowed, which is very difficult to troubleshoot.

Therefore, we finally store configuration information in the database mode. Add a configuration information table to the database to store public configuration information and add corresponding management interfaces for maintenance. All systems obtain public configuration information from the same database, which perfectly solves the repetitive configuration problem.

The first is the public configuration base class:

1     public abstract class ConfigInfo2     {3         public abstract string SectionName { get; }4 5         public abstract void RegisterOptions(IServiceCollection services, IConfigurationRoot root);6     }

SectionName is the configuration name. RegisterOptions registers the configuration information (see Options mode) to DI. The default registration container of. net core is IServiceCollection. All configuration classes, such as cache configuration, database configuration, and log configuration, must inherit this class. For example, the cache configuration implementation class is as follows:

1 public sealed class CachingConfigInfo: ConfigInfo 2 {3 /// <summary> 4 // cache Sliding Window time (minutes) 5 /// </summary> 6 public int DefaultSlidingTime {get; set ;} 7 8 /// <summary> 9 // Type 10 /// </summary> 11 public string Type {get; set ;} 12 13 /// <summary> 14 /// parameter 15 /// </summary> 16 public List <CacheServer> Servers {get; set ;} 17 18 public override string SectionName19 {20 get21 {22 return "MicroStrutLibrary: Caching"; 23} 24} 25 26 public override void RegisterOptions (IServiceCollection services, IConfigurationRoot root) 27 {28 services. configure <CachingConfigInfo> (root. getSection (SectionName); 29} 30}

 

Second, configure the source base class. Configuration source refers to the location where public configurations (such as cache, database, log, etc.) are stored, such as databases or Json files. Create a configuration section in etettings. json of each application project to store the current public configuration. For example, the configuration source in the database mode and Json file mode is written in the etettings. json file as follows:

 1 "ConfigurationSource": { 2       "StorageMode": "JsonFile", 3       "Parameter": "D:\\Programs\\OSChina\\MicroStrutLibrary\\Client\\MicroStrutLibrary.Client.SampleWebApp\\applibrary.json" 4 } 5  6 ---------- 7 "ConfigurationSource": { 8       "StorageMode": "Database", 9       "Parameter": "Data Source=XXXXXX;Initial Catalog=MicroStrutLibrary;User Id=OperUser;Password=XXXX;MultipleActiveResultSets=true;Persist Security Info=true"10 }

The code for configuring the source base class is as follows:

 1     public abstract class ConfigSource 2     { 3         private const string SourceSectionName = "MicroStrutLibrary:ConfigurationSource"; 4         private const string DefaultStorageMode = "JsonFile"; 5         private const string DefaultParameter = "appsettings.json"; 6  7         protected string _Parameter; 8  9         public static ConfigSource GetConfigSource()10         {11             IConfiguration configuration = new ConfigurationBuilder()12                 .SetBasePath(Directory.GetCurrentDirectory())13                 .AddJsonFile("appsettings.json")14                 .Build();15 16             IConfigurationSection section = configuration.GetSection(SourceSectionName);17 18             string storageMode = section["StorageMode"] ?? DefaultStorageMode;19             string parameter = section["Parameter"] ?? DefaultParameter;20 21             TypeNameHelperInfo info = TypeNameHelper.GetTypeNameHelperInfo<ConfigSource>(storageMode);22 23             return ReflectionHelper.CreateInstance(info.Type, new object[] { parameter }) as ConfigSource;24         }25 26         public ConfigSource(string parameter)27         {28             this._Parameter = parameter;29         }30 31         public abstract IConfigurationRoot GetConfigurationRoot();32     }

The static method GetConfigSource obtains the configuration source settings from the local configuration file appsettings. json of the application, and then creates data sources such as databases or Json files. For more information about TypeNameHelper, see "Reflection tool ".

The abstract method GetConfigurationRoot needs to be implemented by each specific subclass. The main function is to obtain all the configuration information from the configuration source and generate the IConfiguraionRoot object of the configuration information.

The specific implementation of the Json configuration source is as follows:

1 [TypeName ("JsonFile", "Json configuration file")] 2 public class JsonConfigSource: ConfigSource 3 {4 public JsonConfigSource (string parameter): base (parameter) 5 {6} 7 8 public override IConfigurationRoot GetConfigurationRoot () 9 {10 // JsonConfigurationSource source = new JsonConfigurationSource (); 11 // source. path = _ Parameter; 12 13 // ConfigurationBuilder = new ConfigurationBuilder (); 14 // builder. add (source); 15 16 ConfigurationBuilder builder = new ConfigurationBuilder (); 17 builder. addJsonFile (_ Parameter); 18 19 return builder. build (); 20} 21}

General syntax for configuring the source in Json mode:

{  "MicroStrutLibrary": {    "Caching": {      "DefaultSlidingTime": 20,      "Type": "MicroStrutLibrary.Infrastructure.Core.Caching.DefaultCacheHandler, MicroStrutLibrary.Infrastructure.Core"    },    "Database": {      "ConnectionStrings": [        {          "Name": "MicroStrutLibrary",          "ConnectionString": "Data Source=XXXX;Initial Catalog=MicroStrutLibrary;User Id=OperUser;Password=XXXX;MultipleActiveResultSets=true;Persist Security Info=true",          "ProviderName": "System.Data.SqlClient"        }      ],      "Providers": [        {          "Name": "System.Data.SqlClient",          "Type": "MicroStrutLibrary.Infrastructure.Core.Data.Entity.SqlServerDbContextOptionsBuilderProvider, MicroStrutLibrary.Infrastructure.Core.Data.Entity"        }      ]    }  }}

Finally, add a statement similar to services. AddConfiguration () in ConfigureServices of Startup. cs to register the configuration source. AddConfiguration is an extension method. The specific implementation is as follows:

 1         public static IServiceCollection AddConfiguration(this IServiceCollection services) 2         { 3             if (services == null) 4             { 5                 throw new ArgumentNullException(nameof(services)); 6             } 7  8             ConfigSource configSource = ConfigSource.GetConfigSource(); 9 10             IConfigurationRoot root = configSource.GetConfigurationRoot();11 12             IEnumerable<Type> list = ReflectionHelper.GetSubTypes<ConfigInfo>();13             foreach (Type type in list)14             {15                 ConfigInfo configInfo = Activator.CreateInstance(type) as ConfigInfo;16 17                 configInfo.RegisterOptions(services, root);18             }19 20             return services;21         }

The general process is to obtain the configuration source information, then obtain the ConfigurationRoot from the configuration source, obtain all ConfigInfo subclasses, and create and register them in the DI container. For details about GetSubTypes, refer to "Reflection tool"

 

Cloud-oriented. net core development framework directory

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.