Last active
April 29, 2023 00:23
-
-
Save IEvangelist/43832e769fb742bcfb2c20d8446a9cd2 to your computer and use it in GitHub Desktop.
Proposed new APIs for the `IDistributedCache` interface.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public interface IDistributedCache | |
{ | |
T? GetOrCreate(string key, Func<DistributedCacheEntryOptions, T> factory) | |
{ | |
var bytes = Get(key); | |
if (bytes is { Length: > 0 }) | |
{ | |
var payload = Encoding.UTF8.GetString(bytes); | |
return JsonSerializer.Deserialize<T>(payload); | |
} | |
var options = new DistributedCacheEntryOptions(); | |
var value = factory(options); | |
Set(key, value, options); | |
return value; | |
} | |
byte[]? Get(string key); | |
async Task<T?> GetOrCreateAsync( | |
string key, | |
Func<DistributedCacheEntryOptions, Task<T>> factory, | |
CancellationToken token = default(CancellationToken)) | |
{ | |
var bytes = await GetAsync(key, token); | |
if (bytes is { Length: > 0 }) | |
{ | |
var payload = Encoding.UTF8.GetString(bytes); | |
return JsonSerializer.Deserialize<T>(payload); | |
} | |
var options = new DistributedCacheEntryOptions(); | |
var value = await factory(options); | |
await SetAsync(key, value, options, token); | |
return value; | |
} | |
Task<byte[]?> GetAsync(string key, CancellationToken token = default(CancellationToken)); | |
void Set(string key, byte[] value, DistributedCacheEntryOptions options); | |
Task SetAsync( | |
string key, | |
byte[] value, | |
DistributedCacheEntryOptions options, | |
CancellationToken token = default(CancellationToken)); | |
void Refresh(string key); | |
Task RefreshAsync(string key, CancellationToken token = default(CancellationToken)); | |
void Remove(string key); | |
Task RemoveAsync(string key, CancellationToken token = default(CancellationToken)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi @mgravell,
Absolutely! I agree, but as a default, why not use the
System.Text.Json
? To your point this could be "pluggable", but as a starting point, it seems like a reasonable default.The
byte[]
is one of the things that got me looking at this API in the first place, it could benefit fromReadOnlyMemory<byte>
orReadOnlySequence<byte>
, but thinking about the consumer standpoint, the convenience of generics and custom strong-types (POCOs and the like) are really appealing.I do like what has been implemented for output caching with ASP.NET Core, and I agree that "cache invalidation" should also exist in this API.
I'd love to get more involved with some of these discussions, even if only to be a fly on the wall and listen/learn. Thanks for thinking of me in that regard.