LazyCache icon indicating copy to clipboard operation
LazyCache copied to clipboard

DefaultCacheDurationSeconds ignored in CachingService instance methods

Open r-bennett opened this issue 3 years ago • 2 comments

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

  • OS: Windows 10
  • Framework net5.0
  • LazyCache Version 2.1.3

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

r-bennett avatar Apr 16 '21 11:04 r-bennett

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?

alastairtree avatar Jun 18 '21 09:06 alastairtree

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

neozhu avatar Aug 17 '23 02:08 neozhu