public MemDistCacheFactory(ISyncCacheProvider pollySyncCacheProvider, IDistributedCacheWrapper distributedCacheWrapper, ISystemClock mockableDateTime, ILoggerWrapper <MemDistCache <T> > logger) { _pollySyncCacheProvider = pollySyncCacheProvider; _distributedCacheWrapper = distributedCacheWrapper; _mockableDateTime = mockableDateTime; _logger = logger; }
public void Should_throw_when_cache_provider_is_null() { ISyncCacheProvider cacheProvider = null; Action action = () => Policy.Cache <ResultPrimitive>(cacheProvider, TimeSpan.MaxValue); action.ShouldThrow <ArgumentNullException>().And.ParamName.Should().Be("cacheProvider"); }
public MemCache(ISyncCacheProvider pollySyncCacheProvider, ISystemClock mockableDateTime, TimeSpan defaultCacheDuration, Func <DateTimeOffset, DateTimeOffset> whenDataIsStaleDelegate, ILoggerWrapper <MemCache <T> > logger) { _pollySyncCacheProvider = pollySyncCacheProvider; _mockableDateTime = mockableDateTime; _defaultCacheDuration = defaultCacheDuration; _whenDataIsStaleDelegate = whenDataIsStaleDelegate; _logger = logger; }
internal GenericCacheProvider(ISyncCacheProvider nonGenericCacheProvider) { if (nonGenericCacheProvider == null) { throw new ArgumentNullException(nameof(nonGenericCacheProvider)); } _wrappedCacheProvider = nonGenericCacheProvider; }
/// <summary> /// <para>Builds a <see cref="Policy"/> that will function like a result cache for delegate executions returning a <typeparamref name="TResult"/>.</para> /// <para>Before executing a delegate, checks whether the <paramref name="cacheProvider"/> holds a value for the cache key specified by <see cref="M:Context.ExecutionKey"/>. /// If the <paramref name="cacheProvider"/> contains a value, returns that value and does not execute the governed delegate. If the <paramref name="cacheProvider"/> does not provide a value, executes the governed delegate, stores the value with the <paramref name="cacheProvider"/>, then returns the value. /// </para> /// </summary> /// <param name="cacheProvider">The cache provider.</param> /// <param name="ttlStrategy">A strategy for specifying ttl for values to be cached.</param> /// <param name="onCacheError">Delegate to call if an exception is thrown when attempting to get a value from or put a value into the cache, passing the execution context, the cache key, and the exception.</param> /// <returns>The policy instance.</returns> /// <exception cref="ArgumentNullException">cacheProvider</exception> /// <exception cref="ArgumentNullException">ttlStrategy</exception> public static CachePolicy <TResult> Cache <TResult>(ISyncCacheProvider cacheProvider, ITtlStrategy ttlStrategy, Action <Context, string, Exception> onCacheError = null) { if (cacheProvider == null) { throw new ArgumentNullException(nameof(cacheProvider)); } return(Cache <TResult>(cacheProvider.For <TResult>(), ttlStrategy, DefaultCacheKeyStrategy.Instance.GetCacheKey, onCacheError)); }
/// <summary> /// <para>Builds a <see cref="Policy"/> that will function like a result cache for delegate executions returning a result.</para> /// <para>Before executing a delegate returning a result, checks whether the <paramref name="cacheProvider"/> holds a value for the cache key. /// If the <paramref name="cacheProvider"/> provides a value from cache, returns that value and does not execute the governed delegate. If the <paramref name="cacheProvider"/> does not provide a value, executes the governed delegate, stores the value with the <paramref name="cacheProvider"/>, then returns the value. /// </para> /// </summary> /// <param name="cacheProvider">The cache provider.</param> /// <param name="ttlStrategy">A strategy for specifying ttl for values to be cached.</param> /// <param name="onCacheGet">Delegate to call on a cache hit, when value is returned from cache.</param> /// <param name="onCacheMiss">Delegate to call on a cache miss.</param> /// <param name="onCachePut">Delegate to call on cache put.</param> /// <param name="onCacheGetError">Delegate to call if an exception is thrown when attempting to get a value from the cache, passing the execution context, the cache key, and the exception.</param> /// <param name="onCachePutError">Delegate to call if an exception is thrown when attempting to put a value in the cache, passing the execution context, the cache key, and the exception.</param> /// <returns>The policy instance.</returns> /// <exception cref="System.ArgumentNullException"> /// </exception> /// <exception cref="ArgumentNullException">cacheProvider</exception> /// <exception cref="ArgumentNullException">ttlStrategy</exception> /// <exception cref="ArgumentNullException">onCacheGet</exception> /// <exception cref="ArgumentNullException">onCacheMiss</exception> /// <exception cref="ArgumentNullException">onCachePut</exception> /// <exception cref="ArgumentNullException">onCacheGetError</exception> /// <exception cref="ArgumentNullException">onCachePutError</exception> public static CachePolicy Cache( ISyncCacheProvider cacheProvider, ITtlStrategy ttlStrategy, Action <Context, string> onCacheGet, Action <Context, string> onCacheMiss, Action <Context, string> onCachePut, Action <Context, string, Exception> onCacheGetError, Action <Context, string, Exception> onCachePutError) => Cache(cacheProvider, ttlStrategy, DefaultCacheKeyStrategy.Instance.GetCacheKey, onCacheGet, onCacheMiss, onCachePut, onCacheGetError, onCachePutError);
/// <summary> /// <para>Builds a <see cref="Policy"/> that will function like a result cache for delegate executions returning a result.</para> /// <para>Before executing a delegate returning a result, checks whether the <paramref name="cacheProvider"/> holds a value for the cache key. /// If the <paramref name="cacheProvider"/> provides a value from cache, returns that value and does not execute the governed delegate. If the <paramref name="cacheProvider"/> does not provide a value, executes the governed delegate, stores the value with the <paramref name="cacheProvider"/>, then returns the value. /// </para> /// </summary> /// <param name="cacheProvider">The cache provider.</param> /// <param name="ttl">Duration (ttl) for which to cache values.</param> /// <param name="onCacheGet">Delegate to call on a cache hit, when value is returned from cache.</param> /// <param name="onCacheMiss">Delegate to call on a cache miss.</param> /// <param name="onCachePut">Delegate to call on cache put.</param> /// <param name="onCacheGetError">Delegate to call if an exception is thrown when attempting to get a value from the cache, passing the execution context, the cache key, and the exception.</param> /// <param name="onCachePutError">Delegate to call if an exception is thrown when attempting to put a value in the cache, passing the execution context, the cache key, and the exception.</param> /// <returns>The policy instance.</returns> /// <exception cref="System.ArgumentNullException"> /// </exception> /// <exception cref="ArgumentNullException">cacheProvider</exception> /// <exception cref="ArgumentNullException">onCacheGet</exception> /// <exception cref="ArgumentNullException">onCacheMiss</exception> /// <exception cref="ArgumentNullException">onCachePut</exception> /// <exception cref="ArgumentNullException">onCacheGetError</exception> /// <exception cref="ArgumentNullException">onCachePutError</exception> public static CachePolicy Cache( ISyncCacheProvider cacheProvider, TimeSpan ttl, Action <Context, string> onCacheGet, Action <Context, string> onCacheMiss, Action <Context, string> onCachePut, Action <Context, string, Exception> onCacheGetError, Action <Context, string, Exception> onCachePutError) => Cache(cacheProvider, new RelativeTtl(ttl), DefaultCacheKeyStrategy.Instance.GetCacheKey, onCacheGet, onCacheMiss, onCachePut, onCacheGetError, onCachePutError);
/// <summary> /// <para>Builds a <see cref="Policy" /> that will function like a result cache for delegate executions returning a <typeparamref name="TResult"/>.</para> /// <para>Before executing a delegate, checks whether the <paramref name="cacheProvider" /> holds a value for the cache key determined by applying the <paramref name="cacheKeyStrategy"/> to the execution <see cref="Context"/>. /// If the <paramref name="cacheProvider" /> contains a value, returns that value and does not execute the governed delegate. If the <paramref name="cacheProvider" /> does not provide a value, executes the governed delegate, stores the value with the <paramref name="cacheProvider" />, then returns the value. /// </para> /// </summary> /// <param name="cacheProvider">The cache provider.</param> /// <param name="ttl">Duration (ttl) for which to cache values.</param> /// <param name="cacheKeyStrategy">The cache key strategy.</param> /// <param name="onCacheError">Delegate to call if an exception is thrown when attempting to get a value from or put a value into the cache, passing the execution context, the cache key, and the exception.</param> /// <returns>The policy instance.</returns> /// <exception cref="ArgumentNullException">cacheProvider</exception> /// <exception cref="ArgumentNullException">cacheKeyStrategy</exception> public static CachePolicy <TResult> Cache <TResult>(ISyncCacheProvider cacheProvider, TimeSpan ttl, Func <Context, string> cacheKeyStrategy, Action <Context, string, Exception> onCacheError = null) { if (cacheProvider == null) { throw new ArgumentNullException(nameof(cacheProvider)); } return(Cache <TResult>(cacheProvider.For <TResult>(), new RelativeTtl(ttl), cacheKeyStrategy, onCacheError)); }
/// <summary> /// <para>Builds a <see cref="Policy" /> that will function like a result cache for delegate executions returning a <typeparamref name="TResult"/>.</para> /// <para>Before executing a delegate, checks whether the <paramref name="cacheProvider" /> holds a value for the cache key determined by applying the <paramref name="cacheKeyStrategy"/> to the execution <see cref="Context"/>. /// If the <paramref name="cacheProvider" /> contains a value, returns that value and does not execute the governed delegate. If the <paramref name="cacheProvider" /> does not provide a value, executes the governed delegate, stores the value with the <paramref name="cacheProvider" />, then returns the value. /// </para> /// </summary> /// <param name="cacheProvider">The cache provider.</param> /// <param name="ttlStrategy">A strategy for specifying ttl for values to be cached.</param> /// <param name="cacheKeyStrategy">The cache key strategy.</param> /// <param name="onCacheGet">Delegate to call on a cache hit, when value is returned from cache.</param> /// <param name="onCacheMiss">Delegate to call on a cache miss.</param> /// <param name="onCachePut">Delegate to call on cache put.</param> /// <param name="onCacheGetError">Delegate to call if an exception is thrown when attempting to get a value from the cache, passing the execution context, the cache key, and the exception.</param> /// <param name="onCachePutError">Delegate to call if an exception is thrown when attempting to put a value in the cache, passing the execution context, the cache key, and the exception.</param> /// <returns>The policy instance.</returns> /// <exception cref="ArgumentNullException">cacheProvider</exception> /// <exception cref="ArgumentNullException">ttlStrategy</exception> /// <exception cref="ArgumentNullException">cacheKeyStrategy</exception> /// <exception cref="ArgumentNullException">onCacheGet</exception> /// <exception cref="ArgumentNullException">onCacheMiss</exception> /// <exception cref="ArgumentNullException">onCachePut</exception> /// <exception cref="ArgumentNullException">onCacheGetError</exception> /// <exception cref="ArgumentNullException">onCachePutError</exception> public static CachePolicy <TResult> Cache <TResult>( ISyncCacheProvider <TResult> cacheProvider, ITtlStrategy ttlStrategy, ICacheKeyStrategy cacheKeyStrategy, Action <Context, string> onCacheGet, Action <Context, string> onCacheMiss, Action <Context, string> onCachePut, Action <Context, string, Exception> onCacheGetError, Action <Context, string, Exception> onCachePutError) { return(Cache <TResult>(cacheProvider, ttlStrategy, cacheKeyStrategy.GetCacheKey, onCacheGet, onCacheMiss, onCachePut, onCacheGetError, onCachePutError)); }
/// <summary> /// <para>Builds a <see cref="Policy"/> that will function like a result cache for delegate executions returning a result.</para> /// <para>Before executing a delegate returning a result, checks whether the <paramref name="cacheProvider"/> holds a value for the cache key determined by applying the <paramref name="cacheKeyStrategy"/> to the execution <see cref="Context"/>. /// If the <paramref name="cacheProvider"/> provides a value from cache, returns that value and does not execute the governed delegate. If the <paramref name="cacheProvider"/> does not provide a value, executes the governed delegate, stores the value with the <paramref name="cacheProvider"/>, then returns the value. /// </para> /// </summary> /// <param name="cacheProvider">The cache provider.</param> /// <param name="ttl">Duration (ttl) for which to cache values.</param> /// <param name="cacheKeyStrategy">The cache key strategy.</param> /// <param name="onCacheGet">Delegate to call on a cache hit, when value is returned from cache.</param> /// <param name="onCacheMiss">Delegate to call on a cache miss.</param> /// <param name="onCachePut">Delegate to call on cache put.</param> /// <param name="onCacheGetError">Delegate to call if an exception is thrown when attempting to get a value from the cache, passing the execution context, the cache key, and the exception.</param> /// <param name="onCachePutError">Delegate to call if an exception is thrown when attempting to put a value in the cache, passing the execution context, the cache key, and the exception.</param> /// <returns>The policy instance.</returns> /// <exception cref="System.ArgumentNullException"> /// </exception> /// <exception cref="ArgumentNullException">cacheProvider</exception> /// <exception cref="ArgumentNullException">cacheKeyStrategy</exception> /// <exception cref="ArgumentNullException">onCacheGet</exception> /// <exception cref="ArgumentNullException">onCacheMiss</exception> /// <exception cref="ArgumentNullException">onCachePut</exception> /// <exception cref="ArgumentNullException">onCacheGetError</exception> /// <exception cref="ArgumentNullException">onCachePutError</exception> public static CachePolicy Cache( ISyncCacheProvider cacheProvider, TimeSpan ttl, Func <Context, string> cacheKeyStrategy, Action <Context, string> onCacheGet, Action <Context, string> onCacheMiss, Action <Context, string> onCachePut, Action <Context, string, Exception> onCacheGetError, Action <Context, string, Exception> onCachePutError) { return(Cache(cacheProvider, new RelativeTtl(ttl), cacheKeyStrategy, onCacheGet, onCacheMiss, onCachePut, onCacheGetError, onCachePutError)); }
public void Get_should_return_instance_previously_stored_in_cache() { Mock <Microsoft.Extensions.Caching.Distributed.IDistributedCache> mockDistributedCache = new Mock <Microsoft.Extensions.Caching.Distributed.IDistributedCache>(); string key = "anything"; mockDistributedCache.Setup(idc => idc.Get(It.Is <string>(k => k == key))).Returns(new byte[0] { }).Verifiable(); // Because GetString() is an extension method, we cannot mock it. We mock Get() instead. ISyncCacheProvider <string> provider = mockDistributedCache.Object.AsSyncCacheProvider <string>(); string got = provider.Get(key); mockDistributedCache.Verify(v => v.Get(key), Times.Once); }
/// <summary> /// Initializes a new instance of the <see cref="SerializingCacheProvider{TResult, TSerialized}" /> class. /// </summary> /// <param name="wrappedCacheProvider">The wrapped cache provider.</param> /// <param name="serializer">The serializer.</param> /// <exception cref="System.ArgumentNullException">wrappedCacheProvider </exception> /// <exception cref="System.ArgumentNullException">serializer </exception> public SerializingCacheProvider(ISyncCacheProvider <TSerialized> wrappedCacheProvider, ICacheItemSerializer <object, TSerialized> serializer) { if (wrappedCacheProvider == null) { throw new ArgumentNullException(nameof(wrappedCacheProvider)); } if (serializer == null) { throw new ArgumentNullException(nameof(serializer)); } _wrappedCacheProvider = wrappedCacheProvider; _serializer = serializer; }
public void Get_should_return_null_on_unknown_key() { Mock <Microsoft.Extensions.Caching.Distributed.IDistributedCache> mockDistributedCache = new Mock <Microsoft.Extensions.Caching.Distributed.IDistributedCache>(); string key = "anything"; mockDistributedCache.Setup(idc => idc.Get(It.Is <string>(k => k == key))).Verifiable(); // Because GetString() is an extension method, we cannot mock it. We mock Get() instead. ISyncCacheProvider <string> provider = mockDistributedCache.Object.AsSyncCacheProvider <string>(); string someOtherKey = Guid.NewGuid().ToString(); string got = provider.Get(someOtherKey); mockDistributedCache.Verify(v => v.Get(someOtherKey), Times.Once); got.Should().BeNull(); }
public void Get_should_return_instance_previously_stored_in_cache() { Mock <Microsoft.Extensions.Caching.Distributed.IDistributedCache> mockDistributedCache = new Mock <Microsoft.Extensions.Caching.Distributed.IDistributedCache>(); string key = "anything"; var cachedValue = new byte[] { 0 }; mockDistributedCache.Setup(idc => idc.Get(It.Is <string>(k => k == key))).Returns(cachedValue).Verifiable(); ISyncCacheProvider <byte[]> provider = mockDistributedCache.Object.AsSyncCacheProvider <byte[]>(); byte[] got = provider.Get(key); mockDistributedCache.Verify(v => v.Get(key), Times.Once); got.Should().BeSameAs(cachedValue); }
public void Get_should_return_null_on_unknown_key() { Mock <Microsoft.Extensions.Caching.Distributed.IDistributedCache> mockDistributedCache = new Mock <Microsoft.Extensions.Caching.Distributed.IDistributedCache>(); string key = "anything"; var cachedValue = new byte[] { 0 }; mockDistributedCache.Setup(idc => idc.Get(It.Is <string>(k => k == key))).Returns(cachedValue).Verifiable(); ISyncCacheProvider <byte[]> provider = mockDistributedCache.Object.AsSyncCacheProvider <byte[]>(); string someOtherKey = Guid.NewGuid().ToString(); byte[] got = provider.Get(someOtherKey); mockDistributedCache.Verify(v => v.Get(someOtherKey), Times.Once); got.Should().BeNull(); }
public void Get_should_return_instance_previously_stored_in_cache() { Mock <IDistributedCache> mockDistributedCache = new Mock <IDistributedCache>(); string key = "anything"; string valueToCache = Guid.NewGuid().ToString(); mockDistributedCache.Setup(idc => idc.Get(It.Is <string>(k => k == key))).Returns(Encoding.UTF8.GetBytes(valueToCache)).Verifiable(); // Because GetString() is an extension method, we cannot mock it. We mock Get() instead. ISyncCacheProvider <string> provider = mockDistributedCache.Object.AsSyncCacheProvider <string>(); (bool got, string fromCache) = provider.TryGet(key); got.Should().BeTrue(); mockDistributedCache.Verify(v => v.Get(key), Times.Once); fromCache.Should().Be(valueToCache); }
public void Get_should_return_instance_previously_stored_in_cache() { Mock <IDistributedCache> mockDistributedCache = new Mock <IDistributedCache>(); string key = "anything"; var cachedValue = Encoding.UTF8.GetBytes(Guid.NewGuid().ToString()); mockDistributedCache.Setup(idc => idc.Get(It.Is <string>(k => k == key))).Returns(cachedValue).Verifiable(); ISyncCacheProvider <byte[]> provider = mockDistributedCache.Object.AsSyncCacheProvider <byte[]>(); (bool got, byte[] fromCache) = provider.TryGet(key); got.Should().BeTrue(); mockDistributedCache.Verify(v => v.Get(key), Times.Once); fromCache.Should().BeSameAs(cachedValue); }
public void Put_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 }; ISyncCacheProvider <byte[]> provider = mockDistributedCache.Object.AsSyncCacheProvider <byte[]>(); mockDistributedCache.Setup(idc => idc.Set(It.Is <string>(k => k == key), It.Is <byte[]>(v => v == valueToCache), It.IsAny <DistributedCacheEntryOptions>())).Verifiable(); TimeSpan timespan = TimeSpan.FromSeconds(10); Ttl ttl = new Ttl(timespan, true); provider.Put(key, valueToCache, ttl); mockDistributedCache.Verify(idc => idc.Set(key, valueToCache, It.Is <DistributedCacheEntryOptions>(o => o.SlidingExpiration == timespan))); }
/// <summary> /// <para>Builds a <see cref="Policy" /> that will function like a result cache for delegate executions returning a <typeparamref name="TResult"/>.</para> /// <para>Before executing a delegate, checks whether the <paramref name="cacheProvider" /> holds a value for the cache key determined by applying the <paramref name="cacheKeyStrategy"/> to the execution <see cref="Context"/>. /// If the <paramref name="cacheProvider" /> contains a value, returns that value and does not execute the governed delegate. If the <paramref name="cacheProvider" /> does not provide a value, executes the governed delegate, stores the value with the <paramref name="cacheProvider" />, then returns the value. /// </para> /// </summary> /// <param name="cacheProvider">The cache provider.</param> /// <param name="ttlStrategy">A strategy for specifying ttl for values to be cached.</param> /// <param name="cacheKeyStrategy">The cache key strategy.</param> /// <param name="onCacheGet">Delegate to call on a cache hit, when value is returned from cache.</param> /// <param name="onCacheMiss">Delegate to call on a cache miss.</param> /// <param name="onCachePut">Delegate to call on cache put.</param> /// <param name="onCacheGetError">Delegate to call if an exception is thrown when attempting to get a value from the cache, passing the execution context, the cache key, and the exception.</param> /// <param name="onCachePutError">Delegate to call if an exception is thrown when attempting to put a value in the cache, passing the execution context, the cache key, and the exception.</param> /// <returns>The policy instance.</returns> /// <exception cref="ArgumentNullException">cacheProvider</exception> /// <exception cref="ArgumentNullException">ttlStrategy</exception> /// <exception cref="ArgumentNullException">cacheKeyStrategy</exception> /// <exception cref="ArgumentNullException">onCacheGet</exception> /// <exception cref="ArgumentNullException">onCacheMiss</exception> /// <exception cref="ArgumentNullException">onCachePut</exception> /// <exception cref="ArgumentNullException">onCacheGetError</exception> /// <exception cref="ArgumentNullException">onCachePutError</exception> public static CachePolicy <TResult> Cache <TResult>( ISyncCacheProvider <TResult> cacheProvider, ITtlStrategy ttlStrategy, Func <Context, string> cacheKeyStrategy, Action <Context, string> onCacheGet, Action <Context, string> onCacheMiss, Action <Context, string> onCachePut, Action <Context, string, Exception> onCacheGetError, Action <Context, string, Exception> onCachePutError) { if (cacheProvider == null) { throw new ArgumentNullException(nameof(cacheProvider)); } if (ttlStrategy == null) { throw new ArgumentNullException(nameof(ttlStrategy)); } if (cacheKeyStrategy == null) { throw new ArgumentNullException(nameof(cacheKeyStrategy)); } if (onCacheGet == null) { throw new ArgumentNullException(nameof(onCacheGet)); } if (onCacheMiss == null) { throw new ArgumentNullException(nameof(onCacheMiss)); } if (onCachePut == null) { throw new ArgumentNullException(nameof(onCachePut)); } if (onCachePutError == null) { throw new ArgumentNullException(nameof(onCachePutError)); } if (onCachePutError == null) { throw new ArgumentNullException(nameof(onCachePutError)); } return(new CachePolicy <TResult>(cacheProvider, ttlStrategy, cacheKeyStrategy, onCacheGet, onCacheMiss, onCachePut, onCacheGetError, onCachePutError)); }
public void Put_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 = "something to cache"; ISyncCacheProvider <string> provider = mockDistributedCache.Object.AsSyncCacheProvider <string>(); mockDistributedCache.Setup(idc => idc.Set(It.Is <string>(k => k == key), It.IsAny <byte[]>(), It.IsAny <DistributedCacheEntryOptions>())).Verifiable(); // Because SetString() is an extension method, we cannot mock it. We mock Set() instead. TimeSpan timespan = TimeSpan.FromSeconds(10); Ttl ttl = new Ttl(timespan, true); provider.Put(key, valueToCache, ttl); mockDistributedCache.Verify(idc => idc.Set(key, It.IsAny <byte[]>(), It.Is <DistributedCacheEntryOptions>(o => o.SlidingExpiration == timespan))); }
public void Put_should_put_item_using_passed_nonsliding_ttl() { Mock <IDistributedCache> mockDistributedCache = new Mock <IDistributedCache>(); string key = "anything"; var valueToCache = Encoding.UTF8.GetBytes(Guid.NewGuid().ToString()); ISyncCacheProvider <byte[]> provider = mockDistributedCache.Object.AsSyncCacheProvider <byte[]>(); mockDistributedCache.Setup(idc => idc.Set(It.Is <string>(k => k == key), It.Is <byte[]>(v => v == valueToCache), It.IsAny <DistributedCacheEntryOptions>())).Verifiable(); TimeSpan timespan = TimeSpan.FromSeconds(10); Ttl ttl = new Ttl(timespan, false); provider.Put(key, valueToCache, ttl); mockDistributedCache.Verify(idc => idc.Set(key, valueToCache, It.Is <DistributedCacheEntryOptions>(o => o.AbsoluteExpirationRelativeToNow == timespan))); }
public void Get_should_return_false_on_unknown_key() { Mock <IDistributedCache> mockDistributedCache = new Mock <IDistributedCache>(); string key = "anything"; var cachedValue = Encoding.UTF8.GetBytes(Guid.NewGuid().ToString()); mockDistributedCache.Setup(idc => idc.Get(It.Is <string>(k => k == key))).Returns(cachedValue).Verifiable(); mockDistributedCache.Setup(idc => idc.Get(It.Is <string>(k => k != key))).Returns((byte[])null).Verifiable(); ISyncCacheProvider <byte[]> provider = mockDistributedCache.Object.AsSyncCacheProvider <byte[]>(); string someOtherKey = Guid.NewGuid().ToString(); (bool got, byte[] fromCache) = provider.TryGet(someOtherKey); got.Should().BeFalse(); mockDistributedCache.Verify(v => v.Get(someOtherKey), Times.Once); fromCache.Should().BeNull(); }
internal CachePolicy( ISyncCacheProvider syncCacheProvider, ITtlStrategy ttlStrategy, Func <Context, string> cacheKeyStrategy, Action <Context, string> onCacheGet, Action <Context, string> onCacheMiss, Action <Context, string> onCachePut, Action <Context, string, Exception> onCacheGetError, Action <Context, string, Exception> onCachePutError) { _syncCacheProvider = syncCacheProvider; _ttlStrategy = ttlStrategy; _cacheKeyStrategy = cacheKeyStrategy; _onCacheGet = onCacheGet; _onCachePut = onCachePut; _onCacheMiss = onCacheMiss; _onCacheGetError = onCacheGetError; _onCachePutError = onCachePutError; }
/// <summary> /// <para>Builds a <see cref="Policy"/> that will function like a result cache for delegate executions returning a result.</para> /// <para>Before executing a delegate returning a result, checks whether the <paramref name="cacheProvider"/> holds a value for the cache key determined by applying the <paramref name="cacheKeyStrategy"/> to the execution <see cref="Context"/>. /// If the <paramref name="cacheProvider"/> provides a value from cache, returns that value and does not execute the governed delegate. If the <paramref name="cacheProvider"/> does not provide a value, executes the governed delegate, stores the value with the <paramref name="cacheProvider"/>, then returns the value. /// </para> /// </summary> /// <param name="cacheProvider">The cache provider.</param> /// <param name="ttlStrategy">A strategy for specifying ttl for values to be cached.</param> /// <param name="cacheKeyStrategy">The cache key strategy.</param> /// <param name="onCacheError">Delegate to call if an exception is thrown when attempting to get a value from or put a value into the cache, passing the execution context, the cache key, and the exception.</param> /// <returns>The policy instance.</returns> /// <exception cref="ArgumentNullException">cacheProvider</exception> /// <exception cref="ArgumentNullException">ttlStrategy</exception> /// <exception cref="ArgumentNullException">cacheKeyStrategy</exception> public static CachePolicy Cache(ISyncCacheProvider cacheProvider, ITtlStrategy ttlStrategy, ICacheKeyStrategy cacheKeyStrategy, Action <Context, string, Exception> onCacheError = null) { if (cacheProvider == null) { throw new ArgumentNullException(nameof(cacheProvider)); } if (ttlStrategy == null) { throw new ArgumentNullException(nameof(ttlStrategy)); } if (cacheKeyStrategy == null) { throw new ArgumentNullException(nameof(cacheKeyStrategy)); } onCacheError = onCacheError ?? ((_, __, ___) => { }); Action <Context, string> emptyDelegate = (_, __) => { }; return(Cache(cacheProvider, ttlStrategy, cacheKeyStrategy.GetCacheKey, emptyDelegate, emptyDelegate, emptyDelegate, onCacheError, onCacheError)); }
internal CachePolicy( ISyncCacheProvider syncCacheProvider, ITtlStrategy ttlStrategy, Func <Context, string> cacheKeyStrategy, Action <Context, string> onCacheGet, Action <Context, string> onCacheMiss, Action <Context, string> onCachePut, Action <Context, string, Exception> onCacheGetError, Action <Context, string, Exception> onCachePutError) : base((action, context, cancellationToken) => action(context, cancellationToken), // Pass-through/NOOP policy action, for void-returning calls through a cache policy. PredicateHelper.EmptyExceptionPredicates) { _syncCacheProvider = syncCacheProvider; _ttlStrategy = ttlStrategy; _cacheKeyStrategy = cacheKeyStrategy; _onCacheGet = onCacheGet; _onCachePut = onCachePut; _onCacheMiss = onCacheMiss; _onCacheGetError = onCacheGetError; _onCachePutError = onCachePutError; }
/// <summary> /// <para>Builds a <see cref="Policy"/> that will function like a result cache for delegate executions returning a <typeparamref name="TResult"/>.</para> /// <para>Before executing a delegate, checks whether the <paramref name="cacheProvider"/> holds a value for the cache key specified by <see cref="M:Context.ExecutionKey"/>. /// If the <paramref name="cacheProvider"/> contains a value, returns that value and does not execute the governed delegate. If the <paramref name="cacheProvider"/> does not provide a value, executes the governed delegate, stores the value with the <paramref name="cacheProvider"/>, then returns the value. /// </para> /// </summary> /// <param name="cacheProvider">The cache provider.</param> /// <param name="ttlStrategy">A strategy for specifying ttl for values to be cached.</param> /// <param name="onCacheError">Delegate to call if an exception is thrown when attempting to get a value from or put a value into the cache, passing the execution context, the cache key, and the exception.</param> /// <returns>The policy instance.</returns> /// <exception cref="ArgumentNullException">cacheProvider</exception> /// <exception cref="ArgumentNullException">ttlStrategy</exception> public static CachePolicy <TResult> Cache <TResult>(ISyncCacheProvider <TResult> cacheProvider, ITtlStrategy ttlStrategy, Action <Context, string, Exception> onCacheError = null) { return(Cache <TResult>(cacheProvider, ttlStrategy, DefaultCacheKeyStrategy.Instance.GetCacheKey, onCacheError)); }
/// <summary> /// <para>Builds a <see cref="Policy"/> that will function like a result cache for delegate executions returning a <typeparamref name="TResult"/>.</para> /// <para>Before executing a delegate, checks whether the <paramref name="cacheProvider"/> holds a value for the cache key specified by <see cref="M:Context.ExecutionKey"/>. /// If the <paramref name="cacheProvider"/> contains a value, returns that value and does not execute the governed delegate. If the <paramref name="cacheProvider"/> does not provide a value, executes the governed delegate, stores the value with the <paramref name="cacheProvider"/>, then returns the value. /// </para> /// </summary> /// <param name="cacheProvider">The cache provider.</param> /// <param name="ttl">Duration (ttl) for which to cache values.</param> /// <param name="onCacheError">Delegate to call if an exception is thrown when attempting to get a value from or put a value into the cache, passing the execution context, the cache key, and the exception.</param> /// <returns>The policy instance.</returns> /// <exception cref="ArgumentNullException">cacheProvider</exception> public static CachePolicy <TResult> Cache <TResult>(ISyncCacheProvider <TResult> cacheProvider, TimeSpan ttl, Action <Context, string, Exception> onCacheError = null) { return(Cache <TResult>(cacheProvider, new RelativeTtl(ttl), DefaultCacheKeyStrategy.Instance.GetCacheKey, onCacheError)); }
internal static TResult Implementation <TResult>( ISyncCacheProvider <TResult> cacheProvider, ITtlStrategy ttlStrategy, Func <Context, string> cacheKeyStrategy, Func <Context, CancellationToken, TResult> action, Context context, CancellationToken cancellationToken, 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(action(context, cancellationToken)); } TResult valueFromCache; try { valueFromCache = cacheProvider.Get(cacheKey); } 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 = action(context, cancellationToken); Ttl ttl = ttlStrategy.GetTtl(context); if (ttl.Timespan > TimeSpan.Zero) { try { cacheProvider.Put(cacheKey, result, ttl); onCachePut(context, cacheKey); } catch (Exception ex) { onCachePutError(context, cacheKey, ex); } } return(result); }
/// <summary> /// Provides a strongly <typeparamref name="TCacheFormat"/>-typed version of the supplied <see cref="ISyncCacheProvider"/> /// </summary> /// <typeparam name="TCacheFormat">The type the returned <see cref="ISyncCacheProvider{TResult}"/> will handle.</typeparam> /// <param name="nonGenericCacheProvider">The non-generic cache provider to wrap.</param> /// <returns>ISyncCacheProvider{TCacheFormat}.</returns> public static ISyncCacheProvider <TCacheFormat> For <TCacheFormat>(this ISyncCacheProvider nonGenericCacheProvider) => new GenericCacheProvider <TCacheFormat>(nonGenericCacheProvider);
/// <summary> /// Wraps the <paramref name="serializer"/> around the <paramref name="cacheProvider"/> so that delegate return values of type <typeparamref name="TResult"/> can be stored in the cache as type <typeparamref name="TSerialized"/>. /// </summary> /// <typeparam name="TResult">The return type of delegates which may be executed through the policy.</typeparam> /// <typeparam name="TSerialized">The type of serialized objects to be placed in the cache.</typeparam> /// <param name="cacheProvider">The cache provider.</param> /// <param name="serializer">The serializer.</param> /// <returns>SerializingCacheProvider<TResult, TSerialized>.</returns> public static SerializingCacheProvider <TResult, TSerialized> WithSerializer <TResult, TSerialized>( this ISyncCacheProvider <TSerialized> cacheProvider, ICacheItemSerializer <TResult, TSerialized> serializer) => new SerializingCacheProvider <TResult, TSerialized>(cacheProvider, serializer);