Skip to content

🧑‍💻 Basic Usage

This guide explains how to use the public API exposed by ICoreCache.

By the end of this guide you'll know how to:

  • Store values
  • Retrieve values
  • Remove entries
  • Check if entries exist
  • Invalidate tags
  • Use the Cache-Aside pattern
  • Configure expiration

🧩 Required Namespaces

The examples below rely on implicit usings for readability, so they do not show using directives. In a real project the namespaces are not obvious, because they follow the folder layout rather than the package name:

Type Namespace
ICoreCache Core.Cache.Abstractions
AddCoreCache(), UseCoreCache() Core.Cache.DependencyInjection
CacheOptions Core.Cache.Options
CacheableAttribute Core.Cache.Attributes
CacheEntryOptions Core.Cache.Storage
CacheMetrics Core.Cache.Diagnostics
ICacheBehavior, ICachePipeline Core.Cache.Pipeline.Abstractions
CacheContext and its subclasses Core.Cache.Pipeline.Contexts
CacheDelegate Core.Cache.Pipeline.Delegates

The provider packages follow the same pattern:

Type Namespace
AddCoreCacheRedis(), RedisOptions Core.Cache.Redis.DependencyInjection, Core.Cache.Redis.Options
AddCoreCacheRehydration(), RehydrationOptions Core.Cache.Rehydration.DependencyInjection, Core.Cache.Rehydration.Options

💉 Injecting the Cache Service

public sealed class ProductService(
    ICoreCache cache)
{
}

💾 Store Data

Store an object in the cache.

await cache.SetAsync(
    "products:1",
    product,
    TimeSpan.FromMinutes(10));

An optional collection of tags can also be provided.


📖 Retrieve Data

var product =
    await cache.GetAsync<Product>(
        "products:1");

Returns:

  • the cached object
  • or null if the entry does not exist.

🔍 Check if an Entry Exists

var exists =
    await cache.ExistsAsync(
        "products:1");

🗑️ Remove an Entry

await cache.RemoveAsync(
    "products:1");

⚡ Cache-Aside Pattern

The recommended approach for most scenarios.

var product =
    await cache.GetOrAddAsync(
        key: $"products:{id}",
        factory: async ct =>
            await repository.GetByIdAsync(id, ct),
        expiration: TimeSpan.FromMinutes(10));

The factory executes when the cache entry does not exist.

The operation is handled by the configured cache provider and execution pipeline.


⏳ Using Expiration

Expiration can be specified per operation.

await cache.SetAsync(
    "products",
    products,
    TimeSpan.FromMinutes(5));

If omitted, the entry is stored with no expiration and stays until it is removed or evicted. CacheOptions.DefaultExpiration does not apply here: it is only used by the HTTP response cache. Pass an explicit expiration on every SetAsync or GetOrAddAsync call that needs one.


🏷️ Using Tags

Tags allow related cache entries to be grouped together.

await cache.SetAsync(
    key: $"product:{id}",
    value: product,
    expiration: TimeSpan.FromMinutes(10),
    tags: ["products"]);

Tags can also be provided through GetOrAddAsync().


💥 Invalidate a Tag

await cache.InvalidateByTagAsync(
    "products");

All cache entries associated with that tag are invalidated.


🚦 Working with CancellationToken

All asynchronous operations exposed by ICoreCache support cancellation.

await cache.GetAsync<Product>(
    "products:1",
    cancellationToken);

The cancellation token is propagated through the cache operation.


🧱 Typical Usage Pattern

public async Task<Product?> GetAsync(
    Guid id,
    CancellationToken ct = default)
{
    return await cache.GetOrAddAsync(
        $"products:{id}",
        async cancellationToken =>
            await repository.GetByIdAsync(
                id,
                cancellationToken),
        expiration: TimeSpan.FromMinutes(15),
        tags: ["products"],
        ct: ct);
}

This is the recommended way to integrate the framework into application services.


✅ Best Practices

✅ Prefer GetOrAddAsync() over manually calling GetAsync() and SetAsync().

✅ Use meaningful cache keys.

✅ Group related entries with tags.

✅ Configure sensible expiration values.

✅ Pass the CancellationToken from the calling operation.

✅ Avoid caching frequently changing data.