LazyCache prevent null items being added to cache

I have a method that will expire null items immediately, however I wanted to know if there w as better way to do this for all memory cache items instead of repeating the same code over and over

output = _cache.GetOrAdd(
            "GetRecordUri" + 123, entry => {
                var record = internalGetRecordUri();
                **if(record == null)
                    // expire immediately
                    entry.AbsoluteExpirationRelativeToNow = new TimeSpan(-1, 0, 0, 0);
                else
                    entry.AbsoluteExpirationRelativeToNow = new TimeSpan(1, 0, 0, 0);
                return record;**
            });

The code in bold seems redundant Is there an extension that I can use that will do the same?

>Solution :

You can place this check in separate method:

public void SetAbsoluteExpiration(Entry entry, object value) // change Entry to correct type
{
    if (value is null) // or if (value == null)
        // expire immediately
        entry.AbsoluteExpirationRelativeToNow = new TimeSpan(-1, 0, 0, 0);
    else
        entry.AbsoluteExpirationRelativeToNow = new TimeSpan(1, 0, 0, 0);
}

And call it everywhere you need:

 output = _cache.GetOrAdd(
    "GetRecordUri" + 123, entry => {
        var record = internalGetRecordUri();
        
        SetAbsoluteExpiration(entry, record);

        return record;
    });

Leave a Reply