patterncsharpMinor
Manage a collection of settings in memory with global scope
Viewed 0 times
globalsettingswithcollectionmanagescopememory
Problem
I have a WPF app and a bunch of read/write settings that need to be accessible from various view models. a setting can be any type (
Here is an
here is the settings class, as a singleton:
here is the overrided event args:
```
public class SettingsUpdatedEventArgs : EventArgs
{
public Setting Type { get; private set; }
public object Value { get; private set; }
public SettingsUpdatedEventArgs
string, bool, etc) and all are settable, but only from a 'Settings' view. I also need the view models to be notified when any setting has been updated and which one that was.Here is an
enum with all the settings:public enum Setting
{
SettingA,
SettingB,
//etc
}here is the settings class, as a singleton:
internal sealed class Settings
{
private static volatile Settings _instance;
private static object _syncRoot = new object();
private Dictionary _settings;
private Settings()
{
_settings = new Dictionary();
_settings.Add(Setting.SettingA, 1000);
_settings.Add(Setting.SettingB, 1000);
}
public static Settings Instance
{
get
{
if (_instance == null)
{
lock (_syncRoot)
{
if (_instance == null)
{
_instance = new Settings();
}
}
}
return _instance;
}
}
public void UpdateSetting(Setting key, object value)
{
if (_settings[key] != value)
{
_settings[key] = value;
TriggerNotification(key, value);
}
}
public T GetSetting(Setting key)
{
return (T)_settings[key];
}
public event EventHandler OnSettingsUpdated;
private void TriggerNotification(Setting key, object value)
{
var handler = OnSettingsUpdated;
if (handler != null)
{
handler(this, new SettingsUpdatedEventArgs(key, value));
}
}
}here is the overrided event args:
```
public class SettingsUpdatedEventArgs : EventArgs
{
public Setting Type { get; private set; }
public object Value { get; private set; }
public SettingsUpdatedEventArgs
Solution
Is this a type-safe way to get the setting values?
It's not type-safe in the sense that if you make a mistake in specifying the type parameter of
I've struggled with this issue before and I have created a solution to this that uses generic keys. It's by no means perfect, but you can use it as an inspiration.
It's not type-safe in the sense that if you make a mistake in specifying the type parameter of
GetSetting, or if someone sets setting to the wrong type, you're going to get an exception.I've struggled with this issue before and I have created a solution to this that uses generic keys. It's by no means perfect, but you can use it as an inspiration.
Context
StackExchange Code Review Q#51059, answer score: 2
Revisions (0)
No revisions yet.