-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSettingsManager.cs
73 lines (65 loc) · 1.91 KB
/
SettingsManager.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
using Settings.Serializers;
using System;
using System.Linq;
using System.IO;
using System.Collections.Generic;
namespace Settings
{
public class SettingsManager
{
#region Fields
private string configPath;
private ISerializer provider;
private HashSet<object> sections = new HashSet<object>();
#endregion Fields
public SettingsManager(string _configPath = null)
{
if (string.IsNullOrEmpty(_configPath))
{
_configPath = "appsettings.json";
}
if (!File.Exists(_configPath))
{
var ex = new FileNotFoundException(nameof(_configPath));
throw ex;
}
provider = new JsonSerializer();
configPath = _configPath;
AppDomain.CurrentDomain.ProcessExit += (s, e) => SaveSettings();
LoadSettings();
}
public T GetSection<T>() where T : class, new()
{
var s = sections.OfType<T>().SingleOrDefault();
if (s == null)
{
s = provider.GetSection<T>() ?? new T();
sections.Add(s);
}
return s;
}
private void SetSection(object data)
{
provider.SetSection(data);
}
public void SetSection<T>(T data) where T : new()
{
var s = sections.OfType<T>().SingleOrDefault();
sections?.Remove(s);
sections.Add(data);
provider.SetSection(data);
}
private void LoadSettings()
{
provider.Load(configPath);
}
public void SaveSettings()
{
foreach (var s in sections)
{
SetSection(s);
}
provider.Save(configPath);
}
}
}