Caching
Vitreous provides two caching packages. Use Vitreous.Caching for any IDistributedCache backend (in-memory, SQL, custom). Use Vitreous.Caching.Redis for Redis with tag-based bulk invalidation.
Install and register
Section titled “Install and register”dotnet add package Vitreous.Caching// Register a cache store (your choice of backend)builder.Services.AddDistributedMemoryCache(); // in-process, single-node// or: builder.Services.AddStackExchangeRedisCache(...) // IDistributedCache over Redis
// Register the Vitreous caching behaviorsbuilder.Services.AddVitreousCaching(options =>{ options.KeyPrefix = "vitreous:"; // default — prepended to every cache key});dotnet add package Vitreous.Caching.Redisbuilder.Services.AddVitreousRedisCaching(options =>{ options.ConnectionString = builder.Configuration.GetConnectionString("Redis") ?? "localhost:6379"; options.KeyPrefix = "vitreous:"; // default options.TagPrefix = "vtag:"; // default — prefix for Redis Sets used in tag tracking});Do not call AddVitreousCaching() alongside AddVitreousRedisCaching() — the Redis package is self-contained and registers everything internally.
Keys are stored as {KeyPrefix}:{CacheKey} with exactly one : separator (a prefix that already ends in : is not doubled), identically for both backends.
Other options (the Redis backend has the same ones):
DefaultAbsoluteExpiration— TTL for queries that set neither expiration. Defaultnull(never expires).EnableStampedeProtection— concurrent misses for the same key share one handler call. Defaulttrue.JsonSerializerOptions— used by the default serializer. Register your ownIVitreousCacheSerializerto replace it.
Values are stored together with their result type, so two queries that share a cache key but return different types get a miss instead of each other’s data. All options are listed in the options reference.
Making a query cacheable
Section titled “Making a query cacheable”Implement ICacheableQuery<TResult> instead of IQuery<TResult>:
public sealed record GetOrderQuery(Guid OrderId) : ICacheableQuery<OrderDto>{ public string CacheKey => $"order:{OrderId}"; public TimeSpan? AbsoluteExpiration => TimeSpan.FromMinutes(5); public TimeSpan? SlidingExpiration => null;}CacheKeymust uniquely represent the query — include every parameter that influences the result.AbsoluteExpirationtakes precedence overSlidingExpirationif both are set.SlidingExpirationresets the TTL on each cache hit. Not supported by the Redis backend (see Sliding expiration).- The handler interface (
IQueryHandler<,>) is unchanged.
Invalidating cache entries after a command
Section titled “Invalidating cache entries after a command”Implement IInvalidatesCache on any command:
public sealed record CreateOrderCommand(Guid CustomerId) : ICommand<Guid>, IInvalidatesCache{ IReadOnlyList<string> IInvalidatesCache.CacheKeys => ["orders:list"]; IReadOnlyList<string> IInvalidatesCache.InvalidatesTags => []; // tags: Redis backend only}Invalidation only runs when the command returns a success result. Cache removal failures are logged as warnings and do not fail the command.
Behavior pipeline order
Section titled “Behavior pipeline order”TracingBehavior ← DevUI, always outermost └─ LoggingBehavior ← your custom behaviors └─ ValidationBehavior ← Vitreous.FluentValidation, registered before caching └─ CacheInvalidationBehavior └─ CachingBehavior ← innermost; returns cached value before the handler is called └─ handlerRedis specifics
Section titled “Redis specifics”Tag-based invalidation
Section titled “Tag-based invalidation”Tags allow invalidating many cache entries at once without knowing every key individually.
public sealed record GetOrderQuery(Guid OrderId) : ICacheableQuery<OrderDto>{ public string CacheKey => $"order:{OrderId}"; public TimeSpan? AbsoluteExpiration => TimeSpan.FromMinutes(5); public TimeSpan? SlidingExpiration => null; public IReadOnlyList<string> Tags => ["orders", $"order:{OrderId}"];}
// Invalidates the "orders" tag — removes every key stored under itpublic sealed record CreateOrderCommand(Guid CustomerId) : ICommand<Guid>, IInvalidatesCache{ IReadOnlyList<string> IInvalidatesCache.CacheKeys => ["orders:list"]; IReadOnlyList<string> IInvalidatesCache.InvalidatesTags => ["orders"];}Internally, each tag is a Redis Set. A value and its tag memberships are written together in one Lua script, and each tag Set expires with the longest-lived entry it holds. RemoveByTagAsync detaches the Set atomically, then deletes its entries in pages with SSCAN and UNLINK, so a large tag never blocks Redis.
If Redis is unreachable, requests keep working: messages that don’t use the cache never touch Redis, and cache reads and writes fail fast and fall back to the handler. The connection created from ConnectionString uses abortConnect=false and reconnects in the background.
Sliding expiration
Section titled “Sliding expiration”SlidingExpiration is not enforced by the Redis backend. If AbsoluteExpiration is null, the SlidingExpiration value is used as a fixed TTL (not a true sliding window). Use the IDistributedCache backend if you need genuine sliding expiration semantics.
Native AOT
Section titled “Native AOT”Cached values are serialized with System.Text.Json, which needs a JsonSerializerContext in AOT apps. See Native AOT and trimming.