Skip to content

[API Proposal]: hybridcache, Add expiration logic to GetOrCreateAsync #6434

Closed as duplicate

Description

@PaulVrugt

Background and motivation

Memorycache has a GetOrCreateAsync method that allows the factory to determine the expiration. This is very useful when caching (for instance) access tokens. The hybridcache currently doesn't have this option. The workaround would be to do a manual get, and then, when the entry is not in the cache, do the factory manually, and do a SetAsync. Howerver, hybridcache doesn't even have a getasync

API Proposal

public abstract ValueTask<T> GetOrCreateAsync<TState, T>(string key, Func<CancellationToken, ValueTask<HybridCacheEntry<T>>> factory,
    IEnumerable<string>? tags = null, CancellationToken cancellationToken = default);

the HybridCacheEntry would contain the value, and the relevant options from HybridCacheEntryOptions

API Usage

return await _cache.GetOrCreateAsync($"CacheKey", async () =>
{
    var tokenResponse = await GetTokenAsync();
    var expiration = tokenResponse.Result.ExpiresIn;
    return new HybridCacheEntry(tokenResponse.Result.AccessToken) { .Expiration = Timespan.FromSeconds(expiration) };
});

Alternative Designs

No response

Risks

No response

Activity

  1. added
    api-suggestion
    on May 13, 2025
  2. jodydonetti commented on Jan 7, 2026

    @jodydonetti
    Contributor

    Hi @PaulVrugt

    As a (temporary?) fix you may look into using the FusionCache based implementation of HybridCache, see here.

    It also has a backplane to keep the cache coherent even in a multi-node environment, and that also works with the HybridCache impl.

    It's a 100% compatible drop-in impl replacement, no code changes required except for 1 line during setup.

    Hope this helps.

    NB: FusionCache creator here, just to be clear.

  3. locked and limited conversation to collaborators on May 24, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-suggestionarea-caching-hybrid

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions