Caching with H.Necessaire: Cachers, Expiry and Ephemeral Types
Get-or-add caching with sliding or absolute expiration, housekeeping, and the reusable EphemeralType base.
Applies to H.Necessaire 4.0.5.
Caching in H.Necessaire is a small, async, typed key/value cache with expiry built in. You ask the registry for an ImACacher<T>, hand it a key and a factory, and the factory only runs when the value isn't already cached.
Install
dotnet add package H.NecessaireGet-or-add
ImACacher<Customer> cache = deps.GetCacher<Customer>();
Customer customer = await cache.GetOrAdd($"customer:{id}", async key =>
{
Customer loaded = await repository.LoadAsync(id);
return loaded.ToCacheableItem(key, cacheDuration: TimeSpan.FromMinutes(10));
});The factory returns an ImCachebale<T> (yes, that is the interface's spelling), which you create with the ToCacheableItem extension. On a cache hit the factory is skipped entirely; on a miss, or after the item expired, it runs and its result is stored.
The cacher API
interface ImACacher<T> : ImACacher
{
Task<T> GetOrAdd(string id, Func<string, Task<ImCachebale<T>>> cacheableItemFactory);
Task<T> AddOrUpdate(string id, Func<string, Task<ImCachebale<T>>> cacheableItemFactory);
Task<OperationResult<T>> TryGet(string id);
}
interface ImACacher
{
Task Clear(params string[] ids);
Task ClearAll();
Task RunHousekeepingSession();
}GetOrAddreturns the cached value, running the factory only when there isn't one.AddOrUpdatealways runs the factory and replaces whatever was cached.TryGetnever runs a factory. It returns a failedOperationResultwhen the key isn't cached (or has expired).Clearremoves specific keys,ClearAllempties the cache.
Choosing how an item expires
value.ToCacheableItem(key, cacheDuration: TimeSpan.FromMinutes(5)); // expires 5 minutes after it was last used
value.ToCacheableItem(key, expiresAt: DateTime.UtcNow.AddHours(1)); // expires at a point in time
value.ToCacheableItem(key); // never expiresSliding vs. absolute expiration
When you give an item a duration, expiry is sliding by default: every successful read pushes the validity window forward, so frequently used entries stay cached. If you want a hard deadline regardless of use, switch sliding off:
value.ToCacheableItem(key, cacheDuration: TimeSpan.FromMinutes(5)).DontSlideExpiration(); // AbsoluteExpiration() is an aliasWhen are expired items removed?
A housekeeping session runs on a timer and drops expired items, so an expired entry can linger briefly until the next sweep. The sweep interval is configurable with CachingHousekeepingIntervalInSeconds (see the configuration reference), and you can trigger one yourself with RunHousekeepingSession().
One cacher per value type
The cache manager keeps a single cacher for each T: asking for GetCacher<int>() twice gives you the same instance, and its keys are shared by everyone who caches ints. Prefix your keys ("customer:42") or cache a dedicated wrapper type if several components might collide. GetCacher<T>(cacherBuildID) also accepts an ID to select a differently-built cacher when one has been registered for it.
Ephemeral types: expiry without a cache
The expiry logic lives in a reusable base, EphemeralType<TPayload>, which CacheableItem<T> extends. It's handy on its own for tokens, one-time codes and anything with a lifetime:
var token = new EphemeralType<string> { Payload = "abc123" }; // valid for 24 hours by default
token.ExpireIn(TimeSpan.FromMinutes(15));
token.IsExpired(); // false
token.IsActive(); // true: valid-from has passed and it hasn't expired
token.GetAge();
token.DoNotExpire();
string raw = token; // implicit conversion to and from the payloadIt exposes CreatedAt, ValidFrom, ValidFor, ExpiresAt and AsOf, plus ExpireAt, ExpireIn and DoNotExpire.
When not to use it
The default cacher is in-memory and per-process: it won't be shared across instances of your app, and it is lost on restart. For shared state, persist through a storage service instead.