To save the configuration in the database
We have an in-depth overview of the various configurationsource that are provided by default in the configuration model in the various configuration sources supported by default and in-depth understanding of the three configuration sources for files (JSON, XML, and INI), and if they still do not meet the configuration requirements in the project, We can also use custom Configurationprovider to support the source of the configuration we want. In terms of how the configuration data is persisted, it should be a very common way to store it in a database, and then we will create a configurationsource for the database that uses the latest entity Framework core to perform database access operations. As a matter of length, it is not possible to introduce a separate description of the Entity Framework core-related programming, and if readers are not familiar with it, you can consult the Entity Framework core online documentation. [This article has been synced to the "ASP. NET Core Framework"]
Directory
I. Use of custom Dbconfigurationsource in the application
Second, applicationsetting & Applicationsettingscontext
Third, Dbconfigurationsource
Iv. Dbconfigurationprovider
V. Extension method Adddatabase
I. Use of custom Dbconfigurationsource in the application
We name this custom Configurationsource Dbconfigurationsource. Before we formally introduce the implementation of it, let's look at its application in the project. We created a console program to demonstrate the application to this dbconfigurationsource. We'll save the configuration in a data table in the SQL Server database and read the configuration using the entity Framework Core, so we need to add the "Microsoft.entityframeworkcore" and " Microsoft.EntityFrameworkCore.SqlServer "The dependencies of these two nuget packages. In addition, our instance program uses the options mode to bind the read configuration to an Options object, so we added "Microsoft.Extensions.DependencyInjection" and " Microsoft.Extensions.Options.ConfigurationExtensions "dependence.
1: {
2: ...
3: "Buildoptions": {
4: ...
5: " copytooutput": "Connectionstring.json"
6: },
8: "dependencies": {
9: ...
Ten: " Microsoft.Extensions.Options.ConfigurationExtensions" : "1.0.0",
One: " Microsoft.Extensions.DependencyInjection" : "1.0.0",
: " Microsoft.Extensions.Configuration.Json" : "1.0.0",
: " Microsoft.EntityFrameworkCore.SqlServer" : "1.0.0",
: " microsoft.entityframeworkcore" : "1.0.0"
15:
16:}
We defined the link string as a configuration in a JSON file named "Connectionstring.json", so we added the package for NuGet " Microsoft.Extensions.Configuration.Json "dependence. The link string defines the definition in this JSON file as follows, and we have modified the "buildoptions/copytooutput" configuration item so that the file can be automatically copied to the output directory at compile time.
1: {
2: "connectionStrings": {
3: " defaultdb": " Server = ...; Database= ...; Uid = ...; PWD = ... "
4: }
5:}
We have written the following program to demonstrate the application for custom Configurationsource (Dbconfigurationsource). We first created a Configurationbuilder object and registered a jsonconfigurationsource that points to the "Connectionstring.json" file. The registration for Dbconfigurationsource is represented on the extension method Adddatabase, which receives two parameters, which represent the name of the link string and the initial configuration data, respectively. The former formal "Connectionstring.json" sets the connection string name "Defaultdb", which is a Dictionary object that provides a raw configuration that exactly can form a profile object. After creating the corresponding configuration object using Configurationbuilder, we use the standard Options programming mode read configuration to bind it 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:};
9:iconfiguration config = new Configurationbuilder ()
Ten: . Addjsonfile ("Connectionstring.json")
One: . Adddatabase ("Defaultdb", initialsettings)
A: . Build ();
14:profile profile = new Servicecollection ()
: . AddOptions ()
A: . configure<profile> (config)
: . Buildserviceprovider ()
: . Getservice<ioptions<profile>> ()
: . Value;
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");
27:public class Profile
28: {
: Public Gender Gender {get; set;}
: public int age {get; set;}
: Public ContactInfo contactinfo {get; set;}
32:}
34:public class ContactInfo
35: {
EmailAddress: Public string {get; set;}
PNS: Public string Phoneno {get; set;}
38:}
40:public enum Gender
41: {
: Male,
: Female
44:}
Second, applicationsetting & Applicationsettingscontext
As shown in the code snippet above, the application for Dbconfigurationsource is only reflected in the extension method Adddatabase that we define for configurationbuilder, so it is very convenient to use. So what is the logical implementation behind this extension method? Dbconfigurationsource uses the entity Framework core to perform data operations in code first, as shown below, Applicationsetting is a Poco type that represents a basic configuration item. We store the key of the configuration item in lowercase. The other applicationsettingscontext is the corresponding dbcontext type.
1: [Table ("ApplicationSettings")]
2:public class Applicationsetting
3: {
4: private string key;
6: [Key]
7: Public string Key
8: {
9: get {return key;}
Ten: set {key = value. Tolowerinvariant (); }
One: }
: [Required]
: [MaxLength (512)]
: Public string Value {get; set;}
: Public applicationsetting ()
: {}
: Public applicationsetting (string key, String value)
: {
: This . Key = key;
: This . Value = value;
: }
25:}
27:public class Applicationsettingscontext:dbcontext
28: {
: Public Applicationsettingscontext (dbcontextoptions options): Base (options)
: {}
: Public dbset<applicationsetting> Settings {get; set;}
33:}
Third, Dbconfigurationsource
As shown below is the definition of Dbconfigurationsource, whose constructor accepts two arguments, the first parameter type is a action<dbcontextoptionsbuilder> delegate object, We use it to set the dbcontextoptions used to create the DbContext, and another optional parameter to specify some configuration items that need to be initialized automatically. Dbconfigurationsource uses these two objects to create a Dbconfigurationprovider object in the overridden build method.
1:public class Dbconfigurationsource:iconfigurationsource
2: {
3: private action<dbcontextoptionsbuilder> _setup;
4: private idictionary<string, string> _initialsettings;
6: Public dbconfigurationsource (action<dbcontextoptionsbuilder> setup, idictionary<string, string> Initialsettings = null)
7: {
8: _setup = setup;
9: _initialsettings = initialsettings;
Ten: }
One: Public iconfigurationprovider Build (iconfigurationbuilder builder)
: {
: return new Dbconfigurationprovider (_setup, _initialsettings);
: }
15:}
Iv. Dbconfigurationprovider
Dbconfigurationprovider is derived from the abstract class Configurationprovider. In the overridden Load method, it creates a Applicationsettingscontext object based on the provided action<dbcontextoptionsbuilder>. The latter is used to read the configuration data from the database and convert it into a Dictionary object and assign it to the Data property representing the configuration dictionary. If there is no data in the data table, the method also uses the 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;
6: Public dbconfigurationprovider (action<dbcontextoptionsbuilder> Setup, idictionary<string, string > Initialsettings)
7: {
8: _setup = setup;
9: _initialsettings = initialsettings?? new Dictionary<string, string> ();
Ten: }
: Public override void Load ()
: {
: dbcontextoptionsbuilder<applicationsettingscontext> builder = new dbcontextoptionsbuilder< Applicationsettingscontext> ();
: _setup (builder);
: using (applicationsettingscontext dbContext = new Applicationsettingscontext (builder). Options))
: {
: dbContext.Database.EnsureCreated ();
: This . Data = DbContext.Settings.Any ()? DbContext.Settings.ToDictionary (IT and it). Key, it and it. Value, Stringcomparer.ordinalignorecase): this. Initialize (DbContext);
: }
: }
At: private idictionary<string, string> Initialize (Applicationsettingscontext dbContext)
: {
+: foreach (var item in _initialsettings)
: {
: dbContext.Settings.Add (item. applicationsetting. Key, item. Value));
: }
£ º return _initialsettings.todictionary (it + it). Key, it and it. Value, stringcomparer.ordinalignorecase);
: }
31:}
V. Extension method Adddatabase
The extension method used to register Dbconfigurationsource in the instance demo adddatabase has the following definition. The method first calls the Configurationbuilder build method to create a configuration object and calls the extension method of the latter getconnectionstring to get 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. Creating a Dbconfigurationsource object specifies that the action<dbcontextoptionsbuilder> will 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:}
To save the configuration in the database