feat: IConfiguration for system and other configurations

This commit is contained in:
2026-02-09 13:15:13 +03:00
parent 32a7e9be24
commit 3b1c291588
4 changed files with 92 additions and 0 deletions

View File

@@ -0,0 +1,50 @@
using System.Collections.Generic;
namespace Engine.Core.Config;
public class BasicConfiguration : IConfiguration
{
public Event<IConfiguration, IConfiguration.ConfigUpdateArguments> OnAdded { get; } = new();
public Event<IConfiguration, IConfiguration.ConfigUpdateArguments> OnSet { get; } = new();
public Event<IConfiguration, IConfiguration.ConfigUpdateArguments> OnRemoved { get; } = new();
private readonly Dictionary<string, object?> values = [];
public IReadOnlyDictionary<string, object?> Values => values;
public T? Get<T>(string key, T? defaultValue = default)
{
if (!values.TryGetValue(key, out object? value))
return defaultValue;
if (value is T castedObject)
return castedObject;
try { return (T?)System.Convert.ChangeType(value, typeof(T)); } catch { }
return defaultValue;
}
public object? Get(string key)
{
values.TryGetValue(key, out object? value);
return value;
}
public bool Has(string key) => values.ContainsKey(key);
public void Remove<T>(string key)
{
if (values.Remove(key))
OnRemoved.Invoke(this, new(key));
}
public void Set<T>(string key, T value)
{
if (!values.TryAdd(key, value))
values[key] = value;
else
OnAdded.Invoke(this, new(key));
OnSet.Invoke(this, new(key));
}
}

View File

@@ -0,0 +1,8 @@
using Engine.Core.Exceptions;
namespace Engine.Core.Config;
public static class ConfigurationExtensions
{
public static T GetRequired<T>(this IConfiguration configuration, string key) => configuration.Get<T>(key) ?? throw new NotFoundException($"Type of {typeof(T).FullName} with the key {key} was not present in the {configuration.GetType().FullName}");
}

View File

@@ -0,0 +1,23 @@
using System.Collections.Generic;
namespace Engine.Core.Config;
public interface IConfiguration
{
static IConfiguration System { get; set; } = new SystemConfiguration();
static IConfiguration Shared { get; set; } = new BasicConfiguration();
Event<IConfiguration, ConfigUpdateArguments> OnAdded { get; }
Event<IConfiguration, ConfigUpdateArguments> OnSet { get; }
Event<IConfiguration, ConfigUpdateArguments> OnRemoved { get; }
IReadOnlyDictionary<string, object?> Values { get; }
bool Has(string key);
object? Get(string key);
T? Get<T>(string key, T? defaultValue = default);
void Set<T>(string key, T value);
void Remove<T>(string key);
readonly record struct ConfigUpdateArguments(string Key);
}

View File

@@ -0,0 +1,11 @@
namespace Engine.Core.Config;
public class SystemConfiguration : BasicConfiguration, IConfiguration
{
public SystemConfiguration()
{
foreach (System.Collections.DictionaryEntry entry in System.Environment.GetEnvironmentVariables())
if (entry is { Key: string key, Value: not null })
Set(key, entry.Value);
}
}