From 33804d002e90d737639c4978eae15389fa627447 Mon Sep 17 00:00:00 2001 From: "Janus C. H. Knudsen" Date: Sun, 25 Jan 2026 17:05:24 +0100 Subject: [PATCH] Adds caching to JSON localization service Introduces a caching mechanism for localization JSON documents to improve performance Prevents repeated file reads by storing parsed JSON documents in memory Adds GetDocument method to manage document retrieval and caching Reduces file system I/O overhead for localization translations --- .../Services/JsonLocalizationService.cs | 25 +++++++++++++++---- 1 file changed, 20 insertions(+), 5 deletions(-) diff --git a/PlanTempus.Application/Features/Localization/Services/JsonLocalizationService.cs b/PlanTempus.Application/Features/Localization/Services/JsonLocalizationService.cs index 0c96748..a01a664 100644 --- a/PlanTempus.Application/Features/Localization/Services/JsonLocalizationService.cs +++ b/PlanTempus.Application/Features/Localization/Services/JsonLocalizationService.cs @@ -6,6 +6,7 @@ namespace PlanTempus.Application.Features.Localization.Services; public class JsonLocalizationService : ILocalizationService { private readonly string _translationsPath; + private readonly Dictionary _cache = new(); public JsonLocalizationService(IWebHostEnvironment env) { @@ -17,14 +18,11 @@ public class JsonLocalizationService : ILocalizationService public string Get(string key, string? culture = null) { culture ??= CurrentCulture; - var filePath = Path.Combine(_translationsPath, $"{culture}.json"); + var doc = GetDocument(culture); - if (!File.Exists(filePath)) + if (doc == null) return key; - var json = File.ReadAllText(filePath); - var doc = JsonDocument.Parse(json); - var parts = key.Split('.'); JsonElement current = doc.RootElement; @@ -35,6 +33,23 @@ public class JsonLocalizationService : ILocalizationService return current.GetString() ?? key; } + private JsonDocument? GetDocument(string culture) + { + if (_cache.TryGetValue(culture, out var cached)) + return cached; + + var filePath = Path.Combine(_translationsPath, $"{culture}.json"); + + if (!File.Exists(filePath)) + return null; + + var json = File.ReadAllText(filePath); + var doc = JsonDocument.Parse(json); + _cache[culture] = doc; + + return doc; + } + public IEnumerable GetSupportedCultures() { return new List