Last active
May 28, 2019 01:36
-
-
Save mastry/63bc168d9229a806f6b0d4c3fff1319b to your computer and use it in GitHub Desktop.
Strongly Typed Configuration in a DotNet Core EXE
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
class AppSettings | |
{ | |
private IConfigurationRoot _configuration; | |
public AppSettings() | |
{ | |
// Build the config with support for reload on change | |
_configuration = new ConfigurationBuilder() | |
.SetBasePath(Directory.GetCurrentDirectory()) | |
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) | |
.AddEnvironmentVariables() | |
.Build(); | |
// Register for change notifications | |
IChangeToken token = _configuration.GetReloadToken(); | |
token.RegisterChangeCallback(OnAppSettingsChanged, null); | |
_configuration.Bind(this); | |
} | |
// Handle config changes by reloading data | |
private void OnAppSettingsChanged(object _) | |
{ | |
IChangeToken token = _configuration.GetReloadToken(); | |
token.RegisterChangeCallback(OnAppSettingsChanged, null); | |
_configuration.Bind(this); | |
} | |
// DataConnection section of appsettings.json | |
public DataConnectionSettings? DataConnection { get; set; } | |
// BlobConnection section of appsettings.json | |
public BlobConnectionSettings? BlobConnection { get; set; } | |
} |
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
{ | |
"DataConnection": { | |
"DataServiceUrl": "https://aserver.somewhere.com", | |
"MaxConnections": 10 | |
}, | |
"BlobConnection": { | |
"Endpoint": "mystorageaccount", | |
"Container": "mycontainer" | |
} | |
} |
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
// For the BlobConnection sectino of appsettings.json | |
class BlobConnectionSettings | |
{ | |
public string EndPoint { get; set; } = string.Empty; | |
public string Container { get; set; } = string.Empty; | |
} |
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
// For the DataConnection section of appsettings.json | |
class DataConnectionSettings | |
{ | |
public string DataServiceUrl { get; set; } = string.Empty; | |
public int MaxConnections { get; set; } = 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment