using System.Collections.Immutable; using System.Reflection; using Core.Config.Attributes; using Core.Resources; using Microsoft.Extensions.Logging; namespace Core.Config; public class ConfigManager { private readonly ImmutableDictionary _collectionsByEnum; private readonly ImmutableDictionary _collectionsByType; public ConfigManager(ILogger logger, IResourceProvider resourceProvider) { (_collectionsByEnum, _collectionsByType) = LoadConfigCollections(resourceProvider); logger.LogInformation("Loaded {count} config collections", _collectionsByEnum.Count); } public ConfigCollection GetCollection() { return _collectionsByType[typeof(TConfigType)]; } public ConfigCollection GetCollection(ConfigType type) { return _collectionsByEnum[type]; } public TConfig? GetConfig(int id) where TConfig : IConfig { if (_collectionsByType[typeof(TConfig)].TryGet(id, out TConfig? config)) return config; return default; } private static (ImmutableDictionary, ImmutableDictionary) LoadConfigCollections(IResourceProvider resourceProvider) { var builderByEnum = ImmutableDictionary.CreateBuilder(); var builderByType = ImmutableDictionary.CreateBuilder(); IEnumerable types = Assembly.GetExecutingAssembly().GetTypes() .Where(type => type.IsAssignableTo(typeof(IConfig)) && !type.IsAbstract); foreach (Type type in types) { ConfigCollectionAttribute? attribute = type.GetCustomAttribute(); if (attribute == null) continue; ConfigCollection collection = new(resourceProvider.GetJsonResource("data/config/" + attribute.Path), type); builderByEnum.Add(collection.At(0).Type, collection); builderByType.Add(collection.At(0).GetType(), collection); } return (builderByEnum.ToImmutable(), builderByType.ToImmutable()); } }