-
Notifications
You must be signed in to change notification settings - Fork 0
/
VehicleService2.cs
42 lines (33 loc) · 1.36 KB
/
VehicleService2.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
public class VehicleService : IVehicleService
{
private readonly IMemoryCache _memoryCache;
private readonly HttpClient _httpClient;
private readonly string cacheKey = "vehicles";
private readonly string apiUrl = "https://example.com/api/vehicles"; // Replace with your actual API endpoint
public VehicleService(IMemoryCache memoryCache, HttpClient httpClient)
{
_memoryCache = memoryCache;
_httpClient = httpClient;
}
public List<Vehicle> GetVehicles()
{
List<Vehicle> vehicles;
if (!_memoryCache.TryGetValue(cacheKey, out vehicles))
{
vehicles = GetVehiclesFromApiAsync().Result;
_memoryCache.Set(cacheKey, vehicles,
new MemoryCacheEntryOptions()
.SetAbsoluteExpiration(TimeSpan.FromSeconds(60))); // Adjust cache duration as needed
}
return vehicles;
}
private async Task<List<Vehicle>> GetVehiclesFromApiAsync()
{
var response = await _httpClient.GetAsync(apiUrl);
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
var vehicles = JsonSerializer.Deserialize<List<Vehicle>>(content, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
return vehicles;
}
return new List<Vehicle>();