Exemplo n.º 1
0
        public (IAsyncCacheProvider <TResult>, IAsyncPolicy <TResult>) CreateAsyncCachePolicy <TCache, TResult>()
        {
            var memoryIDistributedCache = new MemoryDistributedCache(Options.Create(new MemoryDistributedCacheOptions()));
            IAsyncCacheProvider <TResult> memoryIDistributedCacheProvider;

            if (typeof(TCache) == typeof(string))
            {
                memoryIDistributedCacheProvider = memoryIDistributedCache.AsAsyncCacheProvider <string>().WithSerializer <TResult, string>(new JsonSerializer <TResult>(new JsonSerializerSettings()));
            }
            else if (typeof(TCache) == typeof(byte[]))
            {
                memoryIDistributedCacheProvider = memoryIDistributedCache.AsAsyncCacheProvider <byte[]>().WithSerializer(new ByteArraySerializer()).WithSerializer <TResult, string>(new JsonSerializer <TResult>(new JsonSerializerSettings()));
            }
            else
            {
                throw new ArgumentException($"{nameof(TCache)} must be either {typeof(string).Name} or {typeof(byte).Name}[]", nameof(TCache));
            }

            var policy = Policy.CacheAsync <TResult>(memoryIDistributedCacheProvider, TimeSpan.FromHours(1));

            return(memoryIDistributedCacheProvider, policy);
        }