using System;
using System.Collections.Generic;
using System.IO;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
namespace OSS.Tools.Config
{
public static class ConfigHelper
{
private static IConfiguration config;
public static IConfiguration Configuration
{
get
{
if (config != null) return config;
var basePat = GetBasePath();
config = new ConfigurationBuilder()
.SetBasePath(basePat)
.Add(new JsonConfigurationSource
{
Path = "appsettings.json",
ReloadOnChange = true
}).Build();
return config;
}
set => config = value;
}
private static string GetBasePath()
{
var basePat = Directory.GetCurrentDirectory();
var sepChar = Path.DirectorySeparatorChar;
var binIndex = basePat.IndexOf(string.Concat(sepChar, "bin", sepChar), StringComparison.OrdinalIgnoreCase);
if (binIndex > 0)
{
basePat = basePat.Substring(0, binIndex);
}
return basePat;
}
///
/// Gets a configuration sub-section with the specified key.
///
/// The key of the configuration section.
/// The .
///
/// This method will never return null. If no matching sub-section is found with the specified key,
/// an empty will be returned.
///
public static IConfigurationSection GetSection(string key)
{
return Configuration?.GetSection(key);
}
public static string GetConnectionString(string name)
{
return Configuration.GetConnectionString(name);
}
///
/// Gets the immediate descendant configuration sub-sections.
///
/// The configuration sub-sections.
public static IEnumerable GetChildren()
{
return Configuration?.GetChildren();
}
}
}