alastairtree / LazyCache

An easy to use thread safe in-memory caching service with a simple developer friendly API for c#
https://nuget.org/packages/LazyCache
MIT License
1.71k stars 159 forks source link

DefaultCacheDurationSeconds ignored in CachingService instance methods #152

Open r-bennett opened 3 years ago

r-bennett commented 3 years ago

Describe the bug DefaultCacheDurationSeconds is being ignored in some code paths. It only appears to be used in AppCacheExtensions e.g. extension https://github.com/alastairtree/LazyCache/blob/e38695bf63b1d33d97032e995d7dd5609dd692b3/LazyCache/AppCacheExtensions.cs#L74 but not in the almost equivalent instance method https://github.com/alastairtree/LazyCache/blob/33d055c75b455eacf62add2ca41182b541b47981/LazyCache/CachingService.cs#L182

To Reproduce

            var cache = new CachingService
            {
                DefaultCachePolicy = {DefaultCacheDurationSeconds = 1}
            };

            var res1 = await cache.GetOrAddAsync("foo", async x => DateTime.UtcNow.Second);

            // wait for the item to expire
            await Task.Delay(TimeSpan.FromSeconds(2));

            // same key
            var res2 = await cache.GetOrAddAsync("foo", async x => DateTime.UtcNow.Second);
            // new key
            var res3 = await cache.GetOrAddAsync("bar", async x => DateTime.UtcNow.Second);

            Console.WriteLine(res1);
            Console.WriteLine(res2);
            Console.WriteLine(res3);

Expected behavior A new value generated for each call, with output e.g.

23
25
25

Actual behavior Same value reused for "foo", with output e.g.

23
23
25

Framework and Platform

Additional context Similar to the report in https://github.com/alastairtree/LazyCache/issues/121, although this isn't because of lazy eviction

alastairtree commented 3 years ago

Yeah I think the line https://github.com/alastairtree/LazyCache/blob/33d055c75b455eacf62add2ca41182b541b47981/LazyCache/CachingService.cs#L184 which is currently

return GetOrAddAsync(key, addItemFactory, null);

should be

return cache.GetOrAddAsync(key, addItemFactory, cache.DefaultCachePolicy.BuildOptions());

Could you submit a failing test like your example and a PR to fix please?

neozhu commented 1 year ago

@alastairtree can you merge this PR#190 and update the version to support dotnet 7?