Edwin ZAP
Edwin ZAP

Reputation: 463

Generic way to try get and set in Cache the result of a method

I created a CacheService to store any object in cache. Each time I will use the cache I will do these steps:

string cacheKey = MY_KEY;
var result = await _cacheProvider.TryGet<T>(cacheKey);
if (result.IsSuccessful)
{
     return result.Value;
}

var data = /*...code to get the data...*/ 
await _cacheProvider.Set(cacheKey, data, _settings.LifeTime);
return data;

I would like to avoid doing this every time by creating an helper who can do this. I thought it would be possible with delegates but after some reading, I'm not so sure anymore.

Thanks

Upvotes: 0

Views: 1618

Answers (1)

Sean
Sean

Reputation: 62492

You could add an extension method to the cache provider. Something like this:

public static async Task<T> TryGetOrSet(this ICacheProvider cacheProvider, string cacheKey, ISettings settings, Func<string, T> dataGetter)
{
    var result = await cacheProvider.TryGet<T>(cacheKey);
    if (result.IsSuccessful)
    {
        return result.Value;
    }

    var data = dataGetter(cacheKey);

    await cacheProvider.Set(cacheKey, data, settings.LifeTime);
    return data;
}

How you can call it like this:

var data = await _cacheProvider.TryGetOrSet(cacheKey, _settings, key => codeToGetTheData(key));

Upvotes: 5

Related Questions