Bug: The Cache DefaultAbsoluteExpireTime property work only once
See original GitHub issueWhen upgrading to aspnet zero 11.2.1 (ABP 7.3.0) for .Net 6, the caching configuration in my module broke, because now cacheOptions.DefaultAbsoluteExpireTime is now a DateTimeOffset instead of a Timespan. ( #5422 )
I did the correction and tested it to verify if it was still working as expected, but I saw that after expiring, the cache wasn’t being used anymore. The new object was being fetched and stored, but the next call to the cache fetched the item again, instead of serving it from the cache.
I saw the changes in https://github.com/aspnetboilerplate/aspnetboilerplate/commit/51e3c9e1f7f5508905dd8931eba11fa501d0d633, and saw the reason: the set method stores the object with the already expired time.
See below how to reproduce:
Module.cs
public override void Initialize()
{
IocManager.RegisterAssemblyByConvention(Assembly.GetExecutingAssembly());
this.Configuration.Caching.Configure("MyCache", cache =>
{
// 30sec to have it expire faster for test (I have it configured 15-30min usually)
cache.DefaultAbsoluteExpireTime = DateTimeOffset.Now.AddSeconds(30);
});
}
ClassService.cs
public async Task<IList<Model>> GetCachedDataAsync()
{
IList<Model> list = await cacheManager
.GetCache<string, List<Model>>("MyCache")
.GetAsync(
"MyCacheItem",
async () =>
{
// after expiring the cache, every call to the GetCachedDataAsync method will hit here.
return await this.classServiceRepository.GetAllAsync();
});
return list;
}
To not have a big impact in the existing calls, I created extension methods for the different cache stores used, where it’s in charge of storing the item with the proper absoluteExpireTime. Example:
public static async Task<TValue> GetFromMyCacheAsync<TKey, TValue>(this ITypedCache<TKey, TValue> cache, TKey key, Func<Task<TValue>> factory)
{
TValue result = await cache.GetOrDefaultAsync(key);
if (result == null)
{
result = await factory();
cache.Set(key, result, absoluteExpireTime: DateTimeOffset.Now.AddMinutes(30));
}
return result;
}
Issue Analytics
- State:
- Created a year ago
- Reactions:1
- Comments:13 (7 by maintainers)
Top GitHub Comments
We can consider adding a factory method to get the
AbsoluteExpireTime
and its priority is greater thanDefaultAbsoluteExpireTime
.project and problem reproduction shared in issue https://github.com/aspnetboilerplate/aspnetboilerplate/issues/6577.