Skip to content

Instantly share code, notes, and snippets.

@wchesley
Created May 7, 2025 21:30
Show Gist options
  • Select an option

  • Save wchesley/26683dfc85861799c467823739b8b394 to your computer and use it in GitHub Desktop.

Select an option

Save wchesley/26683dfc85861799c467823739b8b394 to your computer and use it in GitHub Desktop.
IConfigRepository
/// <summary>
/// Interface for configuration repository.
/// </summary>
public interface IConfigRepository
{
Dictionary<string, string> GetSection(string sectionName);
string? GetValue(
string sectionName,
string key);
}
/// <summary>
/// Repository for accessing configuration settings for the application from config.json file.
/// </summary>
public class JsonConfigRepository : IConfigRepository
{
private readonly IConfiguration _config;
public JsonConfigRepository(IConfiguration config)
{
_config = config;
}
/// <summary>
/// Get section by name from config.json file.
/// </summary>
/// <param name="sectionName"></param>
/// <returns>Dictionary of strings for each key value pair listed under give section name. Returns null if Section name doesnt exist.</returns>
public Dictionary<string, string> GetSection(string sectionName)
{
return _config.GetSection(sectionName)
.GetChildren()
.ToDictionary(x => x.Key, x => x.Value ?? string.Empty);
}
/// <summary>
/// Get value from section by key from config.json file.
/// </summary>
/// <param name="sectionName">name of section key lives under</param>
/// <param name="key">Key name associated with value.</param>
/// <returns>string value under given sectionName and Key. May be null if value was not found.</returns>
public string? GetValue(string sectionName, string key)
{
return _config.GetSection(sectionName)?[key];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment