aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--RhSolutions.AddIn/Services/CurrencyClient.cs47
1 files changed, 28 insertions, 19 deletions
diff --git a/RhSolutions.AddIn/Services/CurrencyClient.cs b/RhSolutions.AddIn/Services/CurrencyClient.cs
index e959bfa..f71d55a 100644
--- a/RhSolutions.AddIn/Services/CurrencyClient.cs
+++ b/RhSolutions.AddIn/Services/CurrencyClient.cs
@@ -1,4 +1,5 @@
-using System.Net;
+using Microsoft.Extensions.Caching.Memory;
+using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Xml.Linq;
@@ -8,34 +9,42 @@ namespace RhSolutions.Services;
public class CurrencyClient : ICurrencyClient
{
private readonly HttpClient _httpClient;
+ private readonly IMemoryCache _memoryCache;
private const string _requestAddress = @"https://www.cbr.ru/scripts/XML_daily.asp?date_req=";
public HttpStatusCode StatusCode { get; private set; }
- public CurrencyClient(HttpClient httpClient)
+ public CurrencyClient(HttpClient httpClient, IMemoryCache memoryCache)
{
_httpClient = httpClient;
+ _memoryCache = memoryCache;
}
public async Task<decimal?> GetExchangeRate(DateTime date)
{
- string request = $"{_requestAddress}{date.Date:dd/MM/yyyy}";
- HttpResponseMessage response = await _httpClient.GetAsync(request);
- try
+ if (!_memoryCache.TryGetValue(date, out decimal exchangeRate))
{
- response.EnsureSuccessStatusCode();
- string xml = await response.Content.ReadAsStringAsync();
- XElement valCourses = XElement.Parse(xml);
-
- decimal? exchangeRate = decimal.Parse(valCourses.Elements("Valute")
- .Where(e => e.Element("Name").Value == "Евро")
- .FirstOrDefault()
- .Element("Value").Value);
- return exchangeRate;
- }
- catch
- {
- StatusCode = response.StatusCode;
- return null;
+ string request = $"{_requestAddress}{date.Date:dd/MM/yyyy}";
+ HttpResponseMessage response = await _httpClient.GetAsync(request);
+ try
+ {
+ response.EnsureSuccessStatusCode();
+ string xml = await response.Content.ReadAsStringAsync();
+ XElement valCourses = XElement.Parse(xml);
+ exchangeRate = decimal.Parse(valCourses.Elements("Valute")
+ .Where(e => e.Element("Name").Value == "Евро")
+ .FirstOrDefault()
+ .Element("Value").Value);
+ var cacheEntryOptions = new MemoryCacheEntryOptions()
+ .SetSlidingExpiration(TimeSpan.FromHours(1));
+ _memoryCache.Set(date, exchangeRate, cacheEntryOptions);
+ return exchangeRate;
+ }
+ catch
+ {
+ StatusCode = response.StatusCode;
+ return null;
+ }
}
+ return exchangeRate;
}
} \ No newline at end of file