using System.Collections.Immutable; using Connected.Entities.Caching; using Connected.ServiceModel; namespace Common.Globalization; internal interface ILanguageCache : IEntityCacheClient { Language? Select(string mappings); } /// /// Represents stateful cache of the entities. /// internal class LanguageCache : EntityCacheClient, ILanguageCache { private readonly Dictionary _mappings; public LanguageCache(IEntityCacheContext context) : base(context, Language.CacheKey) { _mappings = new Dictionary(StringComparer.OrdinalIgnoreCase); } private Dictionary Mappings => _mappings; protected override async Task> OnInitializing(IContext context) { var result = await base.OnInitializing(context); await ResetMappings(); return result; } protected override async Task OnInvalidating(IContext context, int id) { var result = await base.OnInvalidating(context, id); await ResetMappings(); return result; } public Language? Select(string mappings) { if (string.IsNullOrWhiteSpace(mappings)) return null; var tokens = mappings.Split(',', StringSplitOptions.RemoveEmptyEntries); foreach (var token in tokens) { if (Mappings.TryGetValue(token.Trim(), out Language? language)) return language; } return null; } private async Task ResetMappings() { Mappings.Clear(); foreach (var language in await All()) { if (string.IsNullOrWhiteSpace(language.Mappings)) continue; var tokens = language.Mappings.Split(',', StringSplitOptions.RemoveEmptyEntries); foreach (var token in tokens) { if (Mappings.TryGetValue(token.Trim(), out _)) continue; Mappings.Add(token.Trim(), language); } } } }