[API Proposal]: Add `GetAsync` to `HybridCache`
- Dominant language
- C#
- Stars
- 3.2k
- Forks
- 894
- Avg merge
- 1d 12h
- Merged PRs (30d)
- 23
Description
### Background and motivation
There are instances, such as session validation, where a consumer only wants to confirm that an item exists in the cache and not create it. This is not currently (directly) possible with the `HybridCache` implementation.
### API Proposal
```csharp
namespace Microsoft.Extensions.Caching.Hybrid;
public abstract class HybridCache
{
public abstract ValueTask GetAsync(string key, HybridCacheEntryOptions? options = null, CancellationToken cancellationToken = default);
}
```
### API Usage
```csharp
public async ValueTask ValidateSession(string sessionId, HybridCache cache)
{
var session = cache.GetAsync(sessionId);
return (session is not null);
}
```
### Alternative Designs
I can make this work using the existing API but I'm not a fan of my solution so if anyone has a better workaround let me know.
```csharp
public async ValueTask GetAsync(string key, HybridCacheEntryOptions? options = null, CancellationToken cancellationToken = default) where T : notnull
{
try
{
return await GetOrCreateAsync(key, _ => throw new CacheMissException(), options, null, cancellationToken);
}
catch (CacheMissException)
{
return default;
}
}
```
More efficient option suggested by @nibdev
```csharp
public static async Task<(bool Found, T? Result)> TryGetAsync(this HybridCache cache, string key) where T : class
{
var factoryCalled = false;
var result = await cache.GetOrCreateAsync(
key,
_ =>
{
factoryCalled = true;
return ValueTask.FromResult(default(T));
},
new HybridCacheEntryOptions
{
Expiration = TimeSpan.Zero,
LocalCacheExpiration = TimeSpan.Zero,
Flags = HybridCacheEntryFlags.DisableLocalCacheWrite | HybridCacheEntryFlags.DisableDistributedCacheWrite
});
return (!factoryCalled, result);
}
```
### Risks
_No response_
Contributor guide
Assessment
This issue has not been assessed yet.