Imports System.IO Imports Newtonsoft.Json Public Class SettingsManager Implements ISettingsManager Public Shared Event InitializingManager As EventHandler Public Event AutoSavingSettings As EventHandler Public Event SavingSettings As EventHandler Public Event SavedSettings As EventHandler Private ReadOnly settingsProvider As New List(Of ISettingsProvider) Private defaultInstance As ISettings = Nothing Private enableAutoSave As Boolean = False Private addedHandler As Boolean = False Public Property ConfigFilePath As String Public ReadOnly Property Instance As ISettings Implements ISettingsManager.Instance Get If defaultInstance Is Nothing Then Load() End If Return defaultInstance End Get End Property Public Property AutoSaveOnExit As Boolean Get Return enableAutoSave End Get Set If enableAutoSave <> Value Then enableAutoSave = Value Select Case enableAutoSave Case True If Not addedHandler Then AddAutoSaveHandler() End If Case False If addedHandler Then RemoveAutoSaveHandler() End If End Select End If End Set End Property Private Sub AddAutoSaveHandler() AddHandler AppDomain.CurrentDomain.ProcessExit, AddressOf AutoSaveSettingsOnExit addedHandler = True End Sub Private Sub RemoveAutoSaveHandler() RemoveHandler AppDomain.CurrentDomain.ProcessExit, AddressOf AutoSaveSettingsOnExit addedHandler = False End Sub Public Sub New() RaiseEvent InitializingManager(Me, EventArgs.Empty) End Sub Public Sub New(fileName As String, autoSaveOnExit As Boolean) Me.New ConfigFilePath = fileName Me.AutoSaveOnExit = autoSaveOnExit End Sub Private Sub AutoSaveSettingsOnExit(sender As Object, e As EventArgs) RaiseEvent AutoSavingSettings(Me, New EventArgs) Save() End Sub Public Sub Save() Implements ISettingsManager.Save If Not String.IsNullOrEmpty(ConfigFilePath) AndAlso defaultInstance IsNot Nothing Then SaveInternal() End If End Sub Public Sub Load() Implements ISettingsManager.Load If Not String.IsNullOrEmpty(ConfigFilePath) AndAlso File.Exists(ConfigFilePath) Then LoadInternal() Else CreateNewInstance() End If End Sub Public Sub Reset() Implements ISettingsManager.Reset Instance.Reset() End Sub Protected Overridable Sub CreateNewInstance() defaultInstance = New Settings defaultInstance.Initialize(settingsProvider) defaultInstance.Reset() End Sub Protected Overridable Sub LoadInternal() defaultInstance = JsonConvert.DeserializeObject(Of Settings)(File.ReadAllText(ConfigFilePath), CreateJsonSerializerSettings) defaultInstance.Initialize(settingsProvider) End Sub Protected Overridable Sub SaveInternal() RaiseEvent SavingSettings(Me, EventArgs.Empty) File.WriteAllText(ConfigFilePath, JsonConvert.SerializeObject(defaultInstance, CreateJsonSerializerSettings)) RaiseEvent SavedSettings(Me, EventArgs.Empty) End Sub Protected Overridable Function CreateJsonSerializerSettings() As JsonSerializerSettings Return New JsonSerializerSettings With { .Formatting = Formatting.Indented, .TypeNameHandling = TypeNameHandling.Auto } End Function End Class