The new configuration of the system used in .NET Core [7]: configuration stored in the database

We " talk about the default configuration supports a variety of sources " and " in-depth understanding of three configurations for the source file (JSON, XML and INI) of " various ConfigurationSource default configuration model provides in-depth detailed introduction, if they still can not meet the configuration requirements of the project, we can also customize ConfigurationProvider to support our desired configuration source. To configure how data is persistent, it will grow in a database should be a very common way to store, then we are creating a ConfigurationSource against the database, it uses the latest Entity Framework Core database access operation to complete . Limited space, we can not for Entity Framework Core-related programming be introduced separately, if readers are not familiar with this, you can access Entity Framework Core online documentation. [This article has been synchronized to the " ASP.NET Framework Core Secret " among]

Contents
I. use in the application custom DbConfigurationSource
two, ApplicationSetting & ApplicationSettingsContext
three, DbConfigurationSource
four, DbConfigurationProvider
five extension method AddDatabase

First, using custom DbConfigurationSource in the application

We named this custom ConfigurationSource DbConfigurationSource. Prior to the formal introduction of its realization unfold, we take a look at its use in the project. We create a console application to demonstrate this DbConfigurationSource application. We will configure a data table stored in the SQL Server database, and using Entity Framework Core to read the configuration, so we need to add for "Microsoft.EntityFrameworkCore" and "Microsoft.EntityFrameworkCore.SqlServer" These two packages NuGet rely. In addition, our example program will use the Options mode configuration binding will read for an Options object, so we added for NuGet package "Microsoft.Extensions.DependencyInjection" and "Microsoft.Extensions.Options.ConfigurationExtensions" of rely.

   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 will link string as defined in a configuration called " connectionString.json JSON document" in, so we add a dependent for NuGet package "Microsoft.Extensions.Configuration.Json" of. Link character string is as follows in this form JSON Definition file, we have modified the "buildOptions / copyToOutput" configuration item to make this file can be copied to the output directory automatically at compile time.

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

We wrote the following program to demonstrate applications for custom ConfigurationSource (DbConfigurationSource) of. We first created a ConfigurationBuilder object and registered a point "connectionString.json" file JsonConfigurationSource. For registration in the reflected DbConfigurationSource extension method AddDatabase, this method takes two parameters, which represent the name and the initial configuration of the data link string. The former official "connectionString.json" connection string name set "defaultDb", which is a dictionary object that provides original configuration just can constitute a Profile object. After creating the corresponding Configuration object using ConfigurationBuilder, we use a standard programming mode read configuration Options to bind to a Profile object.

   1: var initialSettings = new Dictionary<string, string>
   2: {
   3:     ["Gender"]             = "Male",
   4:     ["Age"]                 = "18",
   5:     ["ContactInfo:EmailAddress"]     = "[email protected]",
   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 == "[email protected]");
  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:  

二、ApplicationSetting & ApplicationSettingsContext

As shown in the above code snippet, the application for extension DbConfigurationSource only reflected in the way we as ConfigurationBuilder defined AddDatabase on, so it is very convenient to use, this method has a kind of behind the extended logic to achieve it? DbConfigurationSource using Code First Entity Framework Core manner to data manipulation, ApplicationSetting shown below shows the basic configuration item POCO type, we will configure Key items stored in lowercase. Another is the corresponding ApplicationSettingsContext 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: }

Three, DbConfigurationSource

DbConfigurationSource is defined as shown below, its constructor accepts two parameters, the first parameter of type Action <DbContextOptionsBuilder> delegate object, we use it to create DbContextOptions DbContext used to set, another alternative parameter is used to specify a number of configuration items to be automatically initialized. DbConfigurationSource create a DbConfigurationProvider objects use these two objects in the Build method overridden.

   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: Build public IConfigurationProvider (IConfigurationBuilder builder)
  12:     {
  13:         return new DbConfigurationProvider(_setup, _initialSettings);
  14:     }
  15: }

四、DbConfigurationProvider

DbConfigurationProvider derived from the abstract class ConfigurationProvider. In the Load method of rewriting, it creates an object according ApplicationSettingsContext Action <DbContextOptionsBuilder> provided, and read the configuration data from the database and into a dictionary and assigned to the representative configuration dictionary Data attribute use the latter. If there is no data in the table data, using the method also initializes the configuration of the provided object DbContext added 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: }

Fifth, extension methods AddDatabase

Examples demonstrate the method used to sign extension of AddDatabase DbConfigurationSource have the following definitions. This method first calls the Build method ConfigurationBuilder create a Configuration object, and call the latter the extension method GetConnectionString complete connection string obtained according to the specified connection name string. Next we call the constructor creates a DbConfigurationSource object and registered on ConfigurationBuilder. Creating DbConfigurationSource objects specified Action <DbContextOptionsBuilder> will complete the setting 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: }

 

We " talk about the default configuration supports a variety of sources " and " in-depth understanding of three configurations for the source file (JSON, XML and INI) of " various ConfigurationSource default configuration model provides in-depth detailed introduction, if they still can not meet the configuration requirements of the project, we can also customize ConfigurationProvider to support our desired configuration source. To configure how data is persistent, it will grow in a database should be a very common way to store, then we are creating a ConfigurationSource against the database, it uses the latest Entity Framework Core database access operation to complete . Limited space, we can not for Entity Framework Core-related programming be introduced separately, if readers are not familiar with this, you can access Entity Framework Core online documentation. [This article has been synchronized to the " ASP.NET Framework Core Secret " among]

Contents
I. use in the application custom DbConfigurationSource
two, ApplicationSetting & ApplicationSettingsContext
three, DbConfigurationSource
four, DbConfigurationProvider
five extension method AddDatabase

First, using custom DbConfigurationSource in the application

We named this custom ConfigurationSource DbConfigurationSource. Prior to the formal introduction of its realization unfold, we take a look at its use in the project. We create a console application to demonstrate this DbConfigurationSource application. We will configure a data table stored in the SQL Server database, and using Entity Framework Core to read the configuration, so we need to add for "Microsoft.EntityFrameworkCore" and "Microsoft.EntityFrameworkCore.SqlServer" These two packages NuGet rely. In addition, our example program will use the Options mode configuration binding will read for an Options object, so we added for NuGet package "Microsoft.Extensions.DependencyInjection" and "Microsoft.Extensions.Options.ConfigurationExtensions" of rely.

   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 will link string as defined in a configuration called " connectionString.json JSON document" in, so we add a dependent for NuGet package "Microsoft.Extensions.Configuration.Json" of. Link character string is as follows in this form JSON Definition file, we have modified the "buildOptions / copyToOutput" configuration item to make this file can be copied to the output directory automatically at compile time.

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

We wrote the following program to demonstrate applications for custom ConfigurationSource (DbConfigurationSource) of. We first created a ConfigurationBuilder object and registered a point "connectionString.json" file JsonConfigurationSource. For registration in the reflected DbConfigurationSource extension method AddDatabase, this method takes two parameters, which represent the name and the initial configuration of the data link string. The former official "connectionString.json" connection string name set "defaultDb", which is a dictionary object that provides original configuration just can constitute a Profile object. After creating the corresponding Configuration object using ConfigurationBuilder, we use a standard programming mode read configuration Options to bind to a Profile object.

   1: var initialSettings = new Dictionary<string, string>
   2: {
   3:     ["Gender"]             = "Male",
   4:     ["Age"]                 = "18",
   5:     ["ContactInfo:EmailAddress"]     = "[email protected]",
   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 == "[email protected]");
  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:  

二、ApplicationSetting & ApplicationSettingsContext

As shown in the above code snippet, the application for extension DbConfigurationSource only reflected in the way we as ConfigurationBuilder defined AddDatabase on, so it is very convenient to use, this method has a kind of behind the extended logic to achieve it? DbConfigurationSource using Code First Entity Framework Core manner to data manipulation, ApplicationSetting shown below shows the basic configuration item POCO type, we will configure Key items stored in lowercase. Another is the corresponding ApplicationSettingsContext 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: }

Three, DbConfigurationSource

DbConfigurationSource is defined as shown below, its constructor accepts two parameters, the first parameter of type Action <DbContextOptionsBuilder> delegate object, we use it to create DbContextOptions DbContext used to set, another alternative parameter is used to specify a number of configuration items to be automatically initialized. DbConfigurationSource create a DbConfigurationProvider objects use these two objects in the Build method overridden.

   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: Build public IConfigurationProvider (IConfigurationBuilder builder)
  12:     {
  13:         return new DbConfigurationProvider(_setup, _initialSettings);
  14:     }
  15: }

四、DbConfigurationProvider

DbConfigurationProvider derived from the abstract class ConfigurationProvider. In the Load method of rewriting, it creates an object according ApplicationSettingsContext Action <DbContextOptionsBuilder> provided, and read the configuration data from the database and into a dictionary and assigned to the representative configuration dictionary Data attribute use the latter. If there is no data in the table data, using the method also initializes the configuration of the provided object DbContext added 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: }

Fifth, extension methods AddDatabase

Examples demonstrate the method used to sign extension of AddDatabase DbConfigurationSource have the following definitions. This method first calls the Build method ConfigurationBuilder create a Configuration object, and call the latter the extension method GetConnectionString complete connection string obtained according to the specified connection name string. Next we call the constructor creates a DbConfigurationSource object and registered on ConfigurationBuilder. Creating DbConfigurationSource objects specified Action <DbContextOptionsBuilder> will complete the setting 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: }

 

Guess you like

Origin www.cnblogs.com/webenh/p/11589953.html