SteinTech
SteinTech

Reputation: 4068

Memory Cache doesn't store keys and values as expected in ASP.NET Core app

I have a middleware that loads and writes common site data to memory cache. So far so good, but when I check if the key (and data) exists, it always returns false.

First time I run it, it's expected with no key, but when reloading the page the key isn't there and default data is written again.

Any ideas?

SetCache.cs:

public sealed class SetCache(RequestDelegate next)
{
    public async Task Invoke(HttpContext context, IHttpContextAccessor httpContext, IUtilityFactory utilityFactory, IMemoryCache memory)
    {
        if (!memory.ContainsKey(CommonStatics.Cached))
        {
            ICacheUtility util = utilityFactory.Get<ICacheUtility>();
            ICache cached = new Cache(httpContext);

            await cached.LoadAsync(httpContext);

            memory.Set<ICache>(CommonStatics.Cached, cached, util.CacheEntryOptions);
        }

        await next(context);
    }
}

CacheUtility.cs:

public MemoryCacheEntryOptions CacheEntryOptions => new() { SlidingExpiration = TimeSpan.FromMinutes(20), AbsoluteExpiration = new DateTimeOffset(DateTime.Now.AddDays(2)) };

Extension method ContainsKey:

public static bool ContainsKey(this IMemoryCache cache, string key)
{
    bool result = false;
    PropertyInfo? field = typeof(MemoryCache).GetProperty("EntriesCollection", BindingFlags.NonPublic | BindingFlags.Instance);
    
    if (field.HasValue())
    {
        ICollection? coll = field.GetValue(cache) as ICollection;

        if (!coll.Null())
        {
            foreach (var item in coll)
            {
                var methodInfo = item.GetType().GetProperty("Key");
                string val = methodInfo.GetValue(item).ToString();

                if (val.EqualStr(key))
                {
                    result = true;
                    break;
                }
            }
        }
    }

    return result;
}

Upvotes: 0

Views: 60

Answers (1)

SteinTech
SteinTech

Reputation: 4068

I changed to TryGetValue and with a little modification I think I'll get it to work.

thanks!

    public async Task Invoke(HttpContext context, IHttpContextAccessor httpContext, IUtilityFactory utilityFactory, IMemoryCache memory)
    {
        if (!memory.TryGetValue(CommonStatics.Cached, out ICache _)) {
            ICache cache = new Cache(httpContext);

            await cache.LoadAsync();

            ICacheUtility util = utilityFactory.Get<ICacheUtility>();
            util.SetCache(cache);
        }

        await next(context);
    }
}

Upvotes: 0

Related Questions