/// <summary> /// Async get or create cache value /// </summary> /// <typeparam name="T">Type of the value cached or to be cached</typeparam> /// <param name="cacheKey">Key of the cache</param> /// <param name="valueProviderFunc">Value provider function in case the value is not in the cache</param> /// <param name="cancellationToken">The cancellation token</param> /// <returns>The requested cache value</returns> public async Task <T> GetOrCreateValueAsync <T>(string cacheKey, Func <T> valueProviderFunc, CancellationToken cancellationToken = default) { // Try to get cache value from local cache var localCacheValue = await _inMemoryCacheProvider.GetAsync <T>(cacheKey, cancellationToken); if (localCacheValue != null) { // Touch distributed cache to mark usage but otherwise return the local value _ = _distributedCacheProvider.GetAsync <T>(cacheKey, cancellationToken); return(localCacheValue); } // Try to get cache value from the distributed cache if not found in the local one var distributedCacheValue = await _distributedCacheProvider.GetAsync <T>(cacheKey, cancellationToken); if (distributedCacheValue != null) { // "Download" value to local cache _ = _inMemoryCacheProvider.SetAsync(cacheKey, distributedCacheValue, cancellationToken); return(distributedCacheValue); } // Cache not found in any of the cache providers so obtain it using the given provider function var cacheValueToSet = valueProviderFunc.Invoke(); // Fill in cache _ = _inMemoryCacheProvider.SetAsync(cacheKey, cacheValueToSet, cancellationToken); _ = _distributedCacheProvider.SetAsync(cacheKey, cacheValueToSet, cancellationToken); // Return the obtained value return(cacheValueToSet); }
public async void GetAsync() { // Arrange object cacheKey = "Unit-Test-Cache"; object innerCacheValue = "MockCacheValue"; _innerCacheMock.Setup(ic => ic.TryGetValue(cacheKey, out innerCacheValue)); // Act var obtainedCacheValue = await _cacheProvider.GetAsync <string>(cacheKey.ToString()); // Assert Assert.Equal(innerCacheValue, obtainedCacheValue); }