alastairtree / LazyCache

An easy to use thread safe in-memory caching service with a simple developer friendly API for c#
https://nuget.org/packages/LazyCache
MIT License
1.72k stars 159 forks source link

Allow an item factory to return its own DateTimeOffset #5

Closed scottgerring closed 6 years ago

scottgerring commented 8 years ago

Hi,

Something like the following:

T GetOrAdd<T>(string key, Func<Tuple<T, DateTimeOffset>> addItemFactory, DateTimeOffset absoluteExpiration)

Would be useful for caching resources that return an expiry - e.g. auth tokens.

Do you think this'd fit within the bounds of the project or is it better to simply extend it?

cheers,

Scott.

alastairtree commented 8 years ago

So you need to cache the item, but you don't know for how long until you execute the itemFactory?

I like the idea but the tuple feels like a bit of cludge. Maybe something with a more explicit definition like the below might work?

interface ICacheUntilFactory<T>{
    DateTimeOffset AbsoluteExpiration { get; }
    Func<T> ItemFactory { get; }
}

//then on CachingService
T GetOrAdd<T>(string key,  ICacheUntilFactory<T>)

//and so usage might look like this?
var cachable = new CacheUntil();
cacheable.ItemFactory = () => {
    var response = getToken();
    cachable.AbsoluteExpiration = response.Expires;
    return response.Value;
}

Fancy having a go and sending a PR?

alastairtree commented 6 years ago

This is now fixed in LazyCache 2.0.0-beta2+ which is in prerelease on nuget.org.

cache.GetOrAdd("some-key", entry => {
    entry.SetAbsoluteExpiration(someAbsoluteExpirationDateTimeOffset);
    return GetTheThingToCache();
});

Any feedback is welcome.

ideoclickVanessa commented 5 years ago

I was looking for a solution like this and barely stumbled upon this issue.

May I suggest adding this information to the wiki, especially since it's not super discoverable that the addFactory can pass in the entry when looking at the method signatures?

alastairtree commented 5 years ago

Good idea, thanks! https://github.com/alastairtree/LazyCache/wiki/API-documentation-(v-2.x)#get-or-add-an-item-to-the-cache-for-duration-defined-when-you-generate-the-item-to-cache