This repository has been archived by the owner on Jan 13, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5.6k
/
Copy pathCachedCatalogViewModelService.cs
50 lines (43 loc) · 1.95 KB
/
CachedCatalogViewModelService.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
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.eShopWeb.Web.Extensions;
using Microsoft.eShopWeb.Web.ViewModels;
using Microsoft.Extensions.Caching.Memory;
namespace Microsoft.eShopWeb.Web.Services;
public class CachedCatalogViewModelService : ICatalogViewModelService
{
private readonly IMemoryCache _cache;
private readonly CatalogViewModelService _catalogViewModelService;
public CachedCatalogViewModelService(IMemoryCache cache,
CatalogViewModelService catalogViewModelService)
{
_cache = cache;
_catalogViewModelService = catalogViewModelService;
}
public async Task<IEnumerable<SelectListItem>> GetBrands()
{
return (await _cache.GetOrCreateAsync(CacheHelpers.GenerateBrandsCacheKey(), async entry =>
{
entry.SlidingExpiration = CacheHelpers.DefaultCacheDuration;
return await _catalogViewModelService.GetBrands();
})) ?? new List<SelectListItem>();
}
public async Task<CatalogIndexViewModel> GetCatalogItems(int pageIndex, int itemsPage, int? brandId, int? typeId)
{
var cacheKey = CacheHelpers.GenerateCatalogItemCacheKey(pageIndex, Constants.ITEMS_PER_PAGE, brandId, typeId);
return (await _cache.GetOrCreateAsync(cacheKey, async entry =>
{
entry.SlidingExpiration = CacheHelpers.DefaultCacheDuration;
return await _catalogViewModelService.GetCatalogItems(pageIndex, itemsPage, brandId, typeId);
})) ?? new CatalogIndexViewModel();
}
public async Task<IEnumerable<SelectListItem>> GetTypes()
{
return (await _cache.GetOrCreateAsync(CacheHelpers.GenerateTypesCacheKey(), async entry =>
{
entry.SlidingExpiration = CacheHelpers.DefaultCacheDuration;
return await _catalogViewModelService.GetTypes();
})) ?? new List<SelectListItem>();
}
}