. NET Core adopts a new configuration system [7]: Save the configuration in the database,. netcore

Source: Internet
Author: User

. NET Core adopts a new configuration system [7]: Save the configuration in the database,. netcore

Let's go to "talk about various configuration sources supported by default" and "learn more about three types of files (JSON, XML, and INI) the configuration source in the configuration model provides an in-depth and detailed introduction to the various configurationsources provided by default. If they still cannot meet the Configuration Requirements in the project, we can also customize ConfigurationProvider to support the desired configuration source. As for how to configure data persistence, it should be a very common way to cultivate data stored in the database. Next we will create a database ConfigurationSource, it uses the latest Entity Framework Core to complete database access operations. Due to space limitations, it is impossible for us to introduce the programming related to Entity Framework Core separately. If readers are not familiar with this, you can refer to the online documentation of Entity Framework Core. [This Article has been synchronized to ASP. NET Core framework secrets]

 

Directory
1. Use the custom DbConfigurationSource in the Application
2. ApplicationSetting & ApplicationSettingsContext
Iii. DbConfigurationSource
4. DbConfigurationProvider
5. Extension Method AddDatabase

1. Use the custom DbConfigurationSource in the Application

We name this custom ConfigurationSource DbConfigurationSource. Before introducing its implementation, let's take a look at its application in the project. Create a console program to demonstrate the DbConfigurationSource application. We save the configuration in a data table in the SQL Server database and use Entity Framework Core to read the configuration. Therefore, we need to add. entityFrameworkCore and Microsoft. entityFrameworkCore. sqlServer "dependencies between the two NuGet packages. In addition, our instance program will use the Options mode to bind the read configuration to an Options object, so we added the "Microsoft. extensions. dependencyInjection and Microsoft. extensions. options. configurationExtensions.

   1: {
   2:   ...
   3:   "buildOptions": {
   4:     ...
   5:     "copyToOutput": "connectionString.json"
   6:   },
   7:  
   8:   "dependencies": {
   9:     ...
  10:     "Microsoft.Extensions.Options.ConfigurationExtensions"    : "1.0.0",
  11:     "Microsoft.Extensions.DependencyInjection"                : "1.0.0",
  12:     "Microsoft.Extensions.Configuration.Json"                 : "1.0.0",
  13:     "Microsoft.EntityFrameworkCore.SqlServer"                 : "1.0.0",
  14:     "Microsoft.EntityFrameworkCore"                           : "1.0.0"
  15:   } 
  16: }

We define the link string as the Configuration in a json file named "connectionString. JSON", so we added the dependency for the NuGet package "Microsoft. Extensions. Configuration. Json. The link string is defined in the JSON file in the following format. we modified the "buildOptions/copyToOutput" configuration item so that the file can be automatically copied to the output directory during compilation.

   1: {
   2:   "connectionStrings": {
   3:     "defaultDb":  "Server = ... ; Database=...; Uid = ...; Pwd = ..."
   4:   }
   5: }

We have compiled the following program to demonstrate the application of custom ConfigurationSource (DbConfigurationSource. We first created a ConfigurationBuilder object and registered a JsonConfigurationSource pointing to the "connectionString. json" file. The registration for DbConfigurationSource is reflected in the extension method AddDatabase. This method receives two parameters, which represent the name of The Link string and the initial configuration data respectively. The connection string name "defaultDb" set in the former "connectionString. json" is a dictionary object. The original configuration provided by the former can constitute a Profile object. After using ConfigurationBuilder to create the corresponding Configuration object, we use the standard Options programming mode to read the Configuration and bind it to a Profile object.

   1: var initialSettings = new Dictionary<string, string>
   2: {
   3:     ["Gender"]             = "Male",
   4:     ["Age"]                 = "18",
   5:     ["ContactInfo:EmailAddress"]     = "foobar@outlook.com",
   6:     ["ContactInfo:PhoneNo"]         = "123456789"
   7: };
   8:  
   9: IConfiguration config = new ConfigurationBuilder()
  10:     .AddJsonFile("connectionString.json")
  11:     .AddDatabase("DefaultDb", initialSettings)
  12:     .Build();
  13:  
  14: Profile profile = new ServiceCollection()
  15:     .AddOptions()
  16:     .Configure<Profile>(config)
  17:     .BuildServiceProvider()
  18:     .GetService<IOptions<Profile>>()
  19:     .Value;
  20:  
  21: Debug.Assert(profile.Gender == Gender.Male);
  22: Debug.Assert(profile.Age == 18);
  23: Debug.Assert(profile.ContactInfo.EmailAddress == "foobar@outlook.com");
  24: Debug.Assert(profile.ContactInfo.PhoneNo == "123456789");
  25:  
  26:  
  27: public class Profile
  28: {
  29:     public Gender         Gender { get; set; }
  30:     public int            Age { get; set; }
  31:     public ContactInfo    ContactInfo { get; set; }
  32: }
  33:  
  34: public class ContactInfo
  35: {
  36:     public string EmailAddress { get; set; }
  37:     public string PhoneNo { get; set; }
  38: }
  39:  
  40: public enum Gender
  41: {
  42:     Male,
  43:     Female
  44: }
  45:  

2. ApplicationSetting & ApplicationSettingsContext

As shown in the code snippet above, the application for DbConfigurationSource is only reflected in the extension method AddDatabase defined for ConfigurationBuilder, so it is very convenient to use, what is the logical implementation behind this extension method? DbConfigurationSource uses Entity Framework Core to perform data operations in Code First mode. The following ApplicationSetting indicates the POCO type of the basic configuration item. we store the Key of the configuration item in lowercase. Another ApplicationSettingsContext is the corresponding DbContext type.

   1: [Table("ApplicationSettings")]
   2: public class ApplicationSetting
   3: {
   4:     private string key;
   5:  
   6:     [Key]
   7:     public string Key
   8:     {
   9:         get { return key; }
  10:         set { key = value.ToLowerInvariant(); }
  11:     }
  12:  
  13:     [Required]
  14:     [MaxLength(512)]
  15:     public string Value { get; set; }
  16:  
  17:     public ApplicationSetting()
  18:     {}
  19:  
  20:     public ApplicationSetting(string key, string value)
  21:     {
  22:         this.Key     = key;
  23:         this.Value   = value;
  24:     }
  25: }
  26:  
  27: public class ApplicationSettingsContext : DbContext
  28: {
  29:     public ApplicationSettingsContext(DbContextOptions options) : base(options)
  30:     {}
  31:  
  32:     public DbSet<ApplicationSetting> Settings { get; set; }
  33: }

Iii. DbConfigurationSource

The following is the definition of DbConfigurationSource. Its constructor accepts two parameters. The first parameter type is the delegate object of Action <DbContextOptionsBuilder>, we use it to set the DbContextOptions used to create DbContext. Another optional parameter is used to specify some configuration items that need to be automatically initialized. DbConfigurationSource uses the two objects to create a DbConfigurationProvider object in the override Build method.

   1: public class DbConfigurationSource : IConfigurationSource
   2: {
   3:     private Action<DbContextOptionsBuilder> _setup;
   4:     private IDictionary<string, string> _initialSettings;
   5:  
   6:     public DbConfigurationSource(Action<DbContextOptionsBuilder> setup, IDictionary<string, string> initialSettings = null)
   7:     {
   8:         _setup               = setup;
   9:         _initialSettings     = initialSettings;
  10:     }
  11:     public IConfigurationProvider Build(IConfigurationBuilder builder)
  12:     {
  13:         return new DbConfigurationProvider(_setup, _initialSettings);
  14:     }
  15: }

4. DbConfigurationProvider

DbConfigurationProvider is derived from the abstract class ConfigurationProvider. In the override Load method, it creates the ApplicationSettingsContext object based on the provided Action <DbContextOptionsBuilder>, the latter is used to read configuration Data from the database, convert it to a dictionary object, and assign a value to the Data attribute representing the configuration dictionary. If no data exists in the data table, this method also uses this DbContext object to add the provided Initialization Configuration to the database.

   1: public class DbConfigurationProvider: ConfigurationProvider
   2: {
   3:     private IDictionary<string, string>         _initialSettings;
   4:     private Action<DbContextOptionsBuilder>     _setup;
   5:  
   6:     public DbConfigurationProvider(Action<DbContextOptionsBuilder> setup, IDictionary<string, string> initialSettings)
   7:     {
   8:         _setup               = setup;
   9:         _initialSettings     = initialSettings?? new Dictionary<string, string>() ;
  10:     }
  11:  
  12:     public override void Load()
  13:     {
  14:         DbContextOptionsBuilder<ApplicationSettingsContext> builder = new DbContextOptionsBuilder<ApplicationSettingsContext>();
  15:         _setup(builder);
  16:         using (ApplicationSettingsContext dbContext = new ApplicationSettingsContext(builder.Options))
  17:         {
  18:             dbContext.Database.EnsureCreated();
  19:             this.Data = dbContext.Settings.Any()? dbContext.Settings.ToDictionary(it => it.Key, it => it.Value, StringComparer.OrdinalIgnoreCase): this.Initialize(dbContext);
  20:         }
  21:     }
  22:  
  23:     private IDictionary<string, string> Initialize(ApplicationSettingsContext dbContext)
  24:     {
  25:         foreach (var item in _initialSettings)
  26:         {
  27:             dbContext.Settings.Add(new ApplicationSetting(item.Key, item.Value));
  28:         }
  29:         return _initialSettings.ToDictionary(it => it.Key, it => it.Value, StringComparer.OrdinalIgnoreCase);
  30:     }
  31: }

5. Extension Method AddDatabase

The extension method used to register DbConfigurationSource In the instance demo is defined as follows. This method first calls the Build method of ConfigurationBuilder to create a Configuration object, and calls the extension method GetConnectionString of the latter to obtain the complete connection string based on the specified connection string name. Next we call the constructor to create a DbConfigurationSource object and register it on ConfigurationBuilder. Create the Action <DbContextOptionsBuilder> specified by the DbConfigurationSource object to complete the settings for the connection string.

   1: public static class DbConfigurationExtensions
   2: {
   3:     public static IConfigurationBuilder AddDatabase(this IConfigurationBuilder builder, string connectionStringName, IDictionary<string, string> initialSettings = null)
   4:     {
   5:         string connectionString = builder.Build().GetConnectionString(connectionStringName);
   6:         DbConfigurationSource source = new DbConfigurationSource(optionsBuilder => optionsBuilder.UseSqlServer(connectionString), initialSettings);
   7:         builder.Add(source);
   8:         return builder;
   9:     }
  10: }

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.