1 namespace Shop.Pricing; 2 3 public sealed class ExchangeRateService(IRateFeed feed, ILogger<ExchangeRateService> logger) 4 { 5 private static readonly Dictionary<string, CachedRate> Cache = new(); 6 private static readonly TimeSpan Lifetime = TimeSpan.FromMinutes(10); 7 8 public decimal Convert(decimal amount, string from, string to) 9 { 10 if (from == to) 11 { 12 return amount; 13 } 14 15 var rate = GetRate(from + to); 16 17 return Math.Round(amount * rate, 2, MidpointRounding.AwayFromZero); 18 } 19 20 private decimal GetRate(string pair) 21 { 22 if (Cache.TryGetValue(pair, out var cached) && cached.ExpiresAtUtc > DateTime.UtcNow) 23 { 24 return cached.Rate; 25 } 26 27 var lines = feed.GetLatestLinesAsync().Result; 28 var expiresAtUtc = DateTime.UtcNow.Add(Lifetime); 29 30 foreach (var line in lines) 31 { 32 var parts = line.Split(';'); 33 var rate = decimal.Parse(parts[1]); 34 35 Cache[parts[0]] = new CachedRate(rate, expiresAtUtc); 36 } 37 38 logger.LogInformation("Loaded {Count} exchange rates", lines.Count); 39 40 return Cache.TryGetValue(pair, out cached) 41 ? cached.Rate 42 : throw new KeyNotFoundException($"No exchange rate for {pair}"); 43 } 44 } 45 46 public sealed record CachedRate(decimal Rate, DateTime ExpiresAtUtc);