Last active
January 2, 2022 14:37
-
-
Save shahabganji/01612bcf8d05accb082d9baa3241cb90 to your computer and use it in GitHub Desktop.
Blog: Custom Configuration Providers in ASP.NET Core
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class SqlServerConfigurationProvider : ConfigurationProvider , IDisposable | |
{ | |
private readonly SqlServerConfigurationSource _configurationSource; | |
public SqlServerConfigurationProvider(SqlServerConfigurationSource configurationSource) | |
{ | |
_configurationSource = configurationSource; | |
} | |
public override void Load() | |
{ | |
// here you should connect to sql server and fetch the configurations | |
} | |
public void Dispose() | |
{ | |
// cleanup all the resources | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class SqlServerConfigurationSource : IConfigurationSource | |
{ | |
public string Server { get; set; } = "localhost"; | |
public string Database { get; set; } = "ConfigurationDb"; | |
public string User { get; set; } = "sa"; | |
public string Password { get; set; } = "yourStrong(!)Password"; | |
public string Table { get; set; } = "dbo.Configuration"; | |
public string KeyColumn { get; set; } = "Key"; | |
public string ValueColumn { get; set; } = "Value"; | |
public IConfigurationProvider Build(IConfigurationBuilder builder) | |
=> new SqlServerConfigurationProvider(this); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CREATE TABLE dbo.Configuration( | |
[Key] NVarChar(50) NOT NULL PRIMARY KEY | |
, [Value] NVarCHar(50) NOT NULL | |
) | |
GO |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static IHostBuilder CreateHostBuilder(string[] args) => | |
Host.CreateDefaultBuilder(args) | |
.ConfigureAppConfiguration(configure => | |
{ | |
configure.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true); | |
configure.AddSqlServerDb(); | |
}) | |
.ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment