-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathVehicleService.cs
53 lines (44 loc) · 1.78 KB
/
VehicleService.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
43
44
45
46
47
48
49
50
51
52
53
using CachingInmemory.Models;
using Microsoft.Extensions.Caching.Memory;
using System.Net.Http;
using System.Text.Json;
namespace CachingInmemory.Services
{
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()
{
// Send a GET request to the external API
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;
}
// Handle error or return an empty list if the API call fails
return new List<Vehicle>();
}
}
}