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 void Set()
        {
            // Arrange
            string cacheKey             = "Unit-Test-Cache";
            var    cacheValue           = "MockCacheValue";
            var    cacheValueSerialized = JsonSerializer.SerializeToUtf8Bytes(cacheValue);

            _innerCacheMock.Setup(ic => ic.Set(cacheKey, cacheValueSerialized, It.IsAny <DistributedCacheEntryOptions>()));

            // Act
            _cacheProvider.Set(cacheKey, cacheValue);

            // Assert
            _innerCacheMock.Verify(ic => ic.Set(cacheKey, cacheValueSerialized, It.IsAny <DistributedCacheEntryOptions>()));
        }