Skip to content

Getting Started

Aghogho Bernard edited this page May 12, 2026 · 3 revisions

Getting Started

Requirements

  • .NET 8, 9, or 10
  • An ASP.NET Core web application (MVC, Razor Pages, or Minimal APIs)

Installation

Install the core package and one provider:

# Core (required)
dotnet add package CacheWeave.Core

# Choose one provider:
dotnet add package CacheWeave.Redis       # Redis via StackExchange.Redis
dotnet add package CacheWeave.InMemory    # IMemoryCache (dev/test)
dotnet add package CacheWeave.SQLite      # SQLite (edge/embedded)
dotnet add package CacheWeave.DynamoDB    # AWS DynamoDB
dotnet add package CacheWeave.NCache      # Alachisoft NCache
dotnet add package CacheWeave.Memcached   # Memcached via EnyimMemcachedCore
dotnet add package CacheWeave.Faster      # Microsoft FASTER KV

Register in Program.cs

using CacheWeave.Core.Extensions;
using CacheWeave.Redis.Extensions;
using Microsoft.Extensions.Logging;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddCacheWeave(options =>
{
    // Serializer: SystemTextJson (default) or NewtonsoftJson
    options.Serializer = CacheWeaveSerializerType.SystemTextJson;

    // Global key version — bump to invalidate all cached entries at once
    options.KeyVersion = "v1";

    // Default TTL when not specified on the attribute
    options.DefaultExpiry = TimeSpan.FromMinutes(5);

    // Emit OpenTelemetry metrics and Activity spans
    options.EnableMetrics = true;

    // Log level for CacheWeave's internal diagnostics
    options.DiagnosticLogLevel = LogLevel.Debug;

    // GZip compress values before storage (recommended for large payloads)
    options.EnableCompression = false;
});

// Register the Redis provider
builder.Services.AddCacheWeaveRedis(
    builder.Configuration.GetValue<string>("CacheWeave:Redis:ConnectionString")
    ?? "localhost:6379");

// For development/testing, use in-memory instead:
// builder.Services.AddCacheWeaveInMemory();

// Wire [CacheWeave] and [CacheWeaveEvict] attributes into the MVC pipeline.
// This must be called on the IMvcBuilder returned by AddControllers() / AddMvc().
builder.Services.AddControllers().AddCacheWeaveFilters();

Your First Cached Endpoint

using CacheWeave.Core;

[ApiController]
[Route("api/[controller]")]
public class ProductsController(IMediator mediator) : ControllerBase
{
    // Cache the response for 5 minutes.
    // Key: "products:list" + sorted query params (page, pageSize)
    [HttpGet]
    [CacheWeave("products:list", ExpirySeconds = 300, IncludeQueryParams = true)]
    public async Task<IActionResult> GetAll(
        [FromQuery] int page = 1,
        [FromQuery] int pageSize = 20)
    {
        var result = await mediator.Send(new GetProductsQuery { Page = page, PageSize = pageSize });
        return Ok(result);
    }

    // Evict the list cache when a product is created
    [HttpPost]
    [CacheWeaveEvict(Prefix = "products:")]
    public async Task<IActionResult> Create([FromBody] CreateProductCommand cmd)
    {
        var id = await mediator.Send(cmd);
        return CreatedAtAction(nameof(GetAll), new { id }, id);
    }
}

Route Parameters

Route parameters (path segments like {id}) are automatically included in the cache key. This ensures that /products/1 and /products/2 produce different cache entries.

// GET /api/products/42 → key: "products:id=42"
[HttpGet("{id}")]
[CacheWeave("products", ExpirySeconds = 600)]
public async Task<IActionResult> GetById(Guid id)
{
    var product = await mediator.Send(new GetProductByIdQuery(id));
    return product is null ? NotFound() : Ok(product);
}

Framework route values (controller, action, page, area) are always excluded. You can also exclude specific route params or disable route param inclusion entirely -- see Cache Keys for details.

Derived Key (No Explicit Key)

Omit the key entirely and CacheWeave derives it from the controller and action name:

[HttpGet]
[CacheWeave]   // key resolves to "Products.GetAll"
public async Task<IActionResult> GetAll() { ... }

[HttpGet("{id}")]
[CacheWeave]   // key resolves to "Products.GetById:id=42"
public async Task<IActionResult> GetById(Guid id) { ... }

The derived key format is {ControllerName}.{ActionName}. Route params, query params, version, and context segments are still appended as configured.

Next Steps

Clone this wiki locally