Ejemplo n.º 1
0
        /// <summary>
        /// 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>
        /// <returns>The requested cache value</returns>
        public T GetOrCreateValue <T>(string cacheKey, Func <T> valueProviderFunc)
        {
            // Try to get cache value from local cache
            var localCacheValue = _inMemoryCacheProvider.Get <T>(cacheKey);

            if (localCacheValue != null)
            {
                // Touch distributed cache (async way without waiting for the result) to mark usage but otherwise return the local value
                _ = _distributedCacheProvider.GetAsync <T>(cacheKey);
                return(localCacheValue);
            }

            // Try to get cache value from the distributed cache if not found in the local one
            var distributedCacheValue = _distributedCacheProvider.Get <T>(cacheKey);

            if (distributedCacheValue != null)
            {
                // "Download" value to local cache
                _inMemoryCacheProvider.Set(cacheKey, distributedCacheValue);
                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.Set(cacheKey, cacheValueToSet);
            _distributedCacheProvider.Set(cacheKey, cacheValueToSet);

            // Return the obtained value
            return(cacheValueToSet);
        }
        public async void GetAsync()
        {
            // Arrange
            string cacheKey        = "Unit-Test-Cache";
            var    innerCacheValue = JsonSerializer.SerializeToUtf8Bytes("MockCacheValue");

            _innerCacheMock.Setup(ic => ic.GetAsync(cacheKey, It.IsAny <CancellationToken>())).Returns(Task.FromResult(innerCacheValue));

            // Act
            var obtainedCacheValue = await _cacheProvider.GetAsync <string>(cacheKey.ToString());

            // Assert
            _innerCacheMock.Verify(ic => ic.GetAsync(cacheKey, It.IsAny <CancellationToken>()));
            Assert.Equal(JsonSerializer.Deserialize <string>(innerCacheValue), obtainedCacheValue);
        }