-
Notifications
You must be signed in to change notification settings - Fork 0
Configuration
All CacheWeave settings are configured via AddCacheWeave(options => ...) in Program.cs.
builder.Services.AddCacheWeave(options =>
{
options.Enabled = true;
options.GlobalKeyPrefix = "my-app"; // namespaces all keys for this service
options.KeySeparator = ":";
options.KeyVersion = "v1";
options.DefaultExpiry = TimeSpan.FromMinutes(5);
options.DefaultNoCacheCondition = NoCacheCondition.OnErrorOrEmpty;
options.Serializer = CacheWeaveSerializerType.SystemTextJson;
options.EnableCompression = false;
options.EnableMetrics = true;
options.DiagnosticLogLevel = LogLevel.Debug;
});Master runtime toggle. When false, CacheWeave resolves a no-op DisabledCacheProvider — all reads return null (cache miss), all writes and evictions are silently skipped. The rest of the pipeline (filters, key building, stampede protection) is bypassed entirely.
// Disable caching in development without removing the registration
builder.Services.AddCacheWeave(options =>
{
options.Enabled = builder.Environment.IsProduction();
});Can also be driven from configuration:
{
"CacheWeave": {
"Enabled": false
}
}A prefix prepended to every cache key produced by CacheWeave — reads, writes, sliding-expiry refreshes, and evictions (both exact-key and prefix-based). The KeySeparator is inserted between the prefix and the rest of the key.
Primary use case: multiple services sharing the same Redis instance. Without a prefix, a key like products:list is ambiguous. With a prefix it becomes inventory-service:products:list, keeping each service's keyspace isolated.
// inventory-service/Program.cs
options.GlobalKeyPrefix = "inventory-service";
// → all keys: "inventory-service:products:list", "inventory-service:orders:123", …
// warehouse-service/Program.cs
options.GlobalKeyPrefix = "warehouse-service";
// → all keys: "warehouse-service:products:list", …Key assembly order with all options set:
{GlobalKeyPrefix}:{baseKey}:{KeyVersion}:{contextSegment}:{queryParams}:{bodyHash}
Example:
inventory-service:products:list:v2:tenant=acme:page=1
[CacheWeaveEvict] attributes are also affected — the prefix is applied to both Key and Prefix eviction targets, so evictions remain consistent with the keys that were written.
[CacheWeaveEvict(Prefix = "products:")]
// with GlobalKeyPrefix = "my-app" → evicts "my-app:products:*"The character(s) placed between each segment of a cache key.
products:v1:tenant=acme:page=1:pageSize=20
^ ^ ^
| | query params
| context segment
version
Redis users should keep the default ":" — it aligns with Redis namespace conventions and is recognised by tools like RedisInsight.
A global version string injected as the second segment of every key. Bump this to instantly invalidate all cached entries without touching the backing store.
options.KeyVersion = "v2"; // all keys become "base:v2:..."Useful for deployments where the response shape changes and stale cached data would cause errors.
The TTL applied to all cache entries when ExpirySeconds is not set on the attribute.
options.DefaultExpiry = TimeSpan.FromHours(1);Set to null for no default expiry (entries persist until evicted by the provider's own policy).
Controls when CacheWeave skips writing to the cache globally. Individual attributes can override this.
| Value | Behaviour |
|---|---|
Never |
Always cache, regardless of status code or content |
OnError |
Skip caching when the response status is non-2xx |
OnEmpty |
Skip caching when the response body is null, empty string, or empty collection |
OnErrorOrEmpty |
Skip on either condition (default) |
Selects the JSON serializer used to serialize and deserialize cached values.
// Use Newtonsoft.Json (requires Newtonsoft.Json package)
options.Serializer = CacheWeaveSerializerType.NewtonsoftJson;See Serializers for custom serializer registration.
When true, values are GZip-compressed before storage and decompressed on retrieval. Reduces Redis memory usage and network bandwidth at the cost of CPU.
options.EnableCompression = true; // recommended for large JSON payloadsSee Compression for details and benchmarks.
When true, CacheWeave emits OpenTelemetry metrics (hits, misses, sets, evictions, duration) and starts Activity spans for each cache operation.
// Disable in environments where OTel is not configured
options.EnableMetrics = false;See OpenTelemetry for wiring metrics into your OTel pipeline.
The log level used for CacheWeave's internal diagnostic messages (key resolution, hit/miss, write, eviction).
// Surface cache activity in production logs without changing host log filters
options.DiagnosticLogLevel = LogLevel.Information;Messages are emitted under the CacheWeave.Core.Filters.CacheWeaveFilter and CacheWeave.Core.Filters.CacheWeaveEvictFilter categories.
CacheWeave is designed to degrade gracefully when the backing store is unavailable. All cache I/O operations — reads, writes, evictions, and sliding-expiry refreshes — are wrapped in try/catch inside the filters. If an exception is thrown (e.g. Redis connection timeout, network error), CacheWeave:
- Logs a
LogWarningwith the exception details. - Falls through to the controller action (on read failure) or silently skips the write/eviction (on write failure).
- Returns the live response to the caller as normal.
This means a Redis outage degrades to cache-miss behaviour — your application keeps serving requests, just without the caching benefit.
warn: CacheWeave.Core.Filters.CacheWeaveFilter[0]
CacheWeave: cache read failed for 'products:list' — falling through to action
System.TimeoutException: The operation has timed out.
Similarly, if no provider is registered at startup, CacheWeave logs a warning and falls back to a no-op provider rather than throwing at request time:
warn: CacheWeave[0]
CacheWeave: no ICacheProviderInner registered. Call AddCacheWeaveRedis(), AddCacheWeaveInMemory(),
or another provider extension. Falling back to no-op provider — all cache operations are disabled.
No configuration is required to enable this behaviour — it is always active.
You can bind CacheWeaveOptions from configuration:
{
"CacheWeave": {
"KeyVersion": "v1",
"DefaultExpirySeconds": 300,
"EnableMetrics": true,
"DiagnosticLogLevel": "Information",
"Redis": {
"ConnectionString": "my-redis.cache.windows.net:6380,ssl=true,password=..."
}
}
}builder.Services.AddCacheWeave(options =>
{
builder.Configuration.GetSection("CacheWeave").Bind(options);
// Override specific values programmatically if needed
options.Serializer = CacheWeaveSerializerType.NewtonsoftJson;
});