Exemplo n.º 1
0
        public async Task PutAsync_should_put_item_using_passed_nonsliding_ttl()
        {
            Mock <IDistributedCache> mockDistributedCache = new Mock <IDistributedCache>();
            string key          = "anything";
            var    valueToCache = Encoding.UTF8.GetBytes(Guid.NewGuid().ToString());

            IAsyncCacheProvider <byte[]> provider = mockDistributedCache.Object.AsAsyncCacheProvider <byte[]>();

            mockDistributedCache.Setup(idc => idc.SetAsync(It.Is <string>(k => k == key), It.Is <byte[]>(v => v == valueToCache), It.IsAny <DistributedCacheEntryOptions>()
#if NETCOREAPP2_0
                                                           , It.IsAny <CancellationToken>()
#endif
                                                           )).Returns(Task.CompletedTask).Verifiable();

            TimeSpan timespan = TimeSpan.FromSeconds(10);
            Ttl      ttl      = new Ttl(timespan, false);

            await provider.PutAsync(key, valueToCache, ttl, CancellationToken.None, false);

            mockDistributedCache.Verify(idc => idc.SetAsync(key, valueToCache, It.Is <DistributedCacheEntryOptions>(o => o.AbsoluteExpirationRelativeToNow == timespan)
#if NETCOREAPP2_0
                                                            , It.IsAny <CancellationToken>()
#endif
                                                            ));
        }
Exemplo n.º 2
0
        public async Task PutAsync_should_put_item_using_passed_nonsliding_ttl()
        {
            Mock <IDistributedCache> mockDistributedCache = new Mock <IDistributedCache>();
            string key          = "anything";
            var    valueToCache = "something to cache";

            IAsyncCacheProvider <string> provider = mockDistributedCache.Object.AsAsyncCacheProvider <string>();

            mockDistributedCache.Setup(idc => idc.SetAsync(It.Is <string>(k => k == key), It.IsAny <byte[]>(), It.IsAny <DistributedCacheEntryOptions>()
#if !NETCOREAPP1_1
                                                           , It.IsAny <CancellationToken>()
#endif
                                                           )).Returns(Task.CompletedTask).Verifiable(); // Because SetStringAsync() is an extension method, we cannot mock it.  We mock SetAsync() instead.

            TimeSpan timespan = TimeSpan.FromSeconds(10);
            Ttl      ttl      = new Ttl(timespan, false);

            await provider.PutAsync(key, valueToCache, ttl, CancellationToken.None, false);

            mockDistributedCache.Verify(idc => idc.SetAsync(key, It.IsAny <byte[]>(), It.Is <DistributedCacheEntryOptions>(o => o.AbsoluteExpirationRelativeToNow == timespan)
#if !NETCOREAPP1_1
                                                            , It.IsAny <CancellationToken>()
#endif
                                                            ));
        }
 /// <summary>
 /// Puts the specified value in the cache asynchronously.
 /// </summary>
 /// <param name="key">The cache key.</param>
 /// <param name="value">The value to put into the cache.</param>
 /// <param name="ttl">The time-to-live for the cache entry.</param>
 /// <param name="cancellationToken">The cancellation token.</param>
 /// <param name="continueOnCapturedContext">Whether async calls should continue on a captured synchronization context.</param>
 /// <returns>A <see cref="Task" /> which completes when the value has been cached.</returns>
 public async Task PutAsync(string key, object value, Ttl ttl, CancellationToken cancellationToken,
                            bool continueOnCapturedContext)
 {
     await _wrappedCacheProvider.PutAsync(
         key,
         _serializer.Serialize(value),
         ttl,
         cancellationToken,
         continueOnCapturedContext
         ).ConfigureAwait(continueOnCapturedContext);
 }
Exemplo n.º 4
0
        public void PutAsync_should_throw_for_cancellation()
        {
            Mock <Microsoft.Extensions.Caching.Distributed.IDistributedCache> mockDistributedCache = new Mock <Microsoft.Extensions.Caching.Distributed.IDistributedCache>();
            string   key          = "anything";
            var      valueToCache = "something to cache";
            TimeSpan timespan     = TimeSpan.FromSeconds(10);
            Ttl      ttl          = new Ttl(timespan, false);

            IAsyncCacheProvider <string> provider = mockDistributedCache.Object.AsAsyncCacheProvider <string>();

            Func <Task> action = () => provider.PutAsync(key, valueToCache, ttl, new CancellationToken(true), false);

            action.ShouldThrow <OperationCanceledException>();
        }
Exemplo n.º 5
0
        public void PutAsync_should_throw_for_cancellation()
        {
            Mock <IDistributedCache> mockDistributedCache = new Mock <IDistributedCache>();
            string   key          = "anything";
            var      valueToCache = Encoding.UTF8.GetBytes(Guid.NewGuid().ToString());
            TimeSpan timespan     = TimeSpan.FromSeconds(10);
            Ttl      ttl          = new Ttl(timespan, false);

            IAsyncCacheProvider <byte[]> provider = mockDistributedCache.Object.AsAsyncCacheProvider <byte[]>();

            Func <Task> action = () => provider.PutAsync(key, valueToCache, ttl, new CancellationToken(true), false);

            action.ShouldThrow <OperationCanceledException>();
        }
Exemplo n.º 6
0
        public async Task PutAsync_should_put_item_using_passed_sliding_ttl()
        {
            Mock <Microsoft.Extensions.Caching.Distributed.IDistributedCache> mockDistributedCache = new Mock <Microsoft.Extensions.Caching.Distributed.IDistributedCache>();
            string key          = "anything";
            var    valueToCache = new byte[] { 0 };

            IAsyncCacheProvider <byte[]> provider = mockDistributedCache.Object.AsAsyncCacheProvider <byte[]>();

            mockDistributedCache.Setup(idc => idc.SetAsync(It.Is <string>(k => k == key), It.Is <byte[]>(v => v == valueToCache), It.IsAny <DistributedCacheEntryOptions>())).Returns(Task.CompletedTask).Verifiable();

            TimeSpan timespan = TimeSpan.FromSeconds(10);
            Ttl      ttl      = new Ttl(timespan, true);
            await provider.PutAsync(key, valueToCache, ttl, CancellationToken.None, false);

            mockDistributedCache.Verify(idc => idc.SetAsync(key, valueToCache, It.Is <DistributedCacheEntryOptions>(o => o.SlidingExpiration == timespan)));
        }
 Task IAsyncCacheProvider <TCacheFormat> .PutAsync(string key, TCacheFormat value, Ttl ttl, CancellationToken cancellationToken, bool continueOnCapturedContext)
 {
     return(_wrappedCacheProvider.PutAsync(key, value, ttl, cancellationToken, continueOnCapturedContext));
 }
Exemplo n.º 8
0
        internal static async Task <TResult> ImplementationAsync <TResult>(
            IAsyncCacheProvider <TResult> cacheProvider,
            ITtlStrategy <TResult> ttlStrategy,
            Func <Context, string> cacheKeyStrategy,
            Func <Context, CancellationToken, Task <TResult> > action,
            Context context,
            CancellationToken cancellationToken,
            bool continueOnCapturedContext,
            Action <Context, string> onCacheGet,
            Action <Context, string> onCacheMiss,
            Action <Context, string> onCachePut,
            Action <Context, string, Exception> onCacheGetError,
            Action <Context, string, Exception> onCachePutError)
        {
            cancellationToken.ThrowIfCancellationRequested();

            string cacheKey = cacheKeyStrategy(context);

            if (cacheKey == null)
            {
                return(await action(context, cancellationToken).ConfigureAwait(continueOnCapturedContext));
            }

            TResult valueFromCache;

            try
            {
                valueFromCache = await cacheProvider.GetAsync(cacheKey, cancellationToken, continueOnCapturedContext).ConfigureAwait(continueOnCapturedContext);
            }
            catch (Exception ex)
            {
                valueFromCache = default(TResult);
                onCacheGetError(context, cacheKey, ex);
            }
            if (valueFromCache != null && !valueFromCache.Equals(default(TResult)))
            {
                onCacheGet(context, cacheKey);
                return(valueFromCache);
            }
            else
            {
                onCacheMiss(context, cacheKey);
            }

            TResult result = await action(context, cancellationToken).ConfigureAwait(continueOnCapturedContext);

            Ttl ttl = ttlStrategy.GetTtl(context, result);

            if (ttl.Timespan > TimeSpan.Zero && result != null && !result.Equals(default(TResult)))
            {
                try
                {
                    await cacheProvider.PutAsync(cacheKey, result, ttl, cancellationToken, continueOnCapturedContext).ConfigureAwait(continueOnCapturedContext);

                    onCachePut(context, cacheKey);
                }
                catch (Exception ex)
                {
                    onCachePutError(context, cacheKey, ex);
                }
            }

            return(result);
        }