55 lines
1.9 KiB
C#
55 lines
1.9 KiB
C#
|
|
using Core.Exceptions;
|
|||
|
|
using Newtonsoft.Json;
|
|||
|
|
using Newtonsoft.Json.Linq;
|
|||
|
|
|
|||
|
|
namespace Core.Configurations.JsonConfigProvider
|
|||
|
|
{
|
|||
|
|
public static class JsonConfigExtension
|
|||
|
|
{
|
|||
|
|
public static IConfigurationBuilder AddJsonFile(this IConfigurationBuilder builder, string configurationFilePath = "appconfiguration.json", bool? optional = true, bool? reloadOnChange = false)
|
|||
|
|
{
|
|||
|
|
return builder.AddProvider(new JsonConfigProvider(builder, configurationFilePath, optional ?? true, reloadOnChange ?? false));
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
public interface IHasConfigurationFilePath
|
|||
|
|
{
|
|||
|
|
string ConfigurationFilePath { get; }
|
|||
|
|
}
|
|||
|
|
public class JsonConfigProvider : IConfigurationProvider, IHasConfigurationFilePath
|
|||
|
|
{
|
|||
|
|
private readonly IConfigurationBuilder _builder;
|
|||
|
|
private readonly bool _reloadOnChange;
|
|||
|
|
JObject _configuration;
|
|||
|
|
public string ConfigurationFilePath { get; private set; }
|
|||
|
|
|
|||
|
|
public JsonConfigProvider() { }
|
|||
|
|
|
|||
|
|
public JsonConfigProvider(IConfigurationBuilder builder, string configurationFilePath, bool optional, bool reloadOnChange)
|
|||
|
|
{
|
|||
|
|
if (!optional && !File.Exists(configurationFilePath))
|
|||
|
|
throw new ConfigurationException($"File not found, path: {configurationFilePath}");
|
|||
|
|
if (optional && !File.Exists(configurationFilePath))
|
|||
|
|
return;
|
|||
|
|
|
|||
|
|
ConfigurationFilePath = configurationFilePath;
|
|||
|
|
_builder = builder;
|
|||
|
|
_reloadOnChange = reloadOnChange;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
public void Build()
|
|||
|
|
{
|
|||
|
|
using (StreamReader file = File.OpenText(ConfigurationFilePath))
|
|||
|
|
using (JsonTextReader reader = new JsonTextReader(file))
|
|||
|
|
{
|
|||
|
|
_configuration = (JObject)JToken.ReadFrom(reader);
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
public JObject Configuration()
|
|||
|
|
{
|
|||
|
|
return _configuration;
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
}
|