Skip to content

Introduction

Immediate.Cache generates in-memory caches for Immediate.Handlers handlers, with request coalescing, invalidation and read-modify-write built in.

2 min read
Immediate.Cache GitHub repository Immediate.Cache NuGet version Immediate.Cache latest GitHub release Immediate.Cache license

Immediate.Cache caches the responses of Immediate.Handlers handlers. You write a small class, mark it with [CacheFor<THandler>], and describe how a request becomes a cache key; a source generator makes that class derive from ApplicationCache<TRequest, TResponse> and wires up its constructor and DI registration at compile time.

Beyond a plain IMemoryCache lookup, the base class gives you request coalescing (simultaneous callers for the same key share one handler execution), imperative SetValue/RemoveValue invalidation, and an optimistic read-modify-write helper.

Installation

dotnet add package Immediate.Cache

The package ships the runtime types, the source generator and the analyzers together. It targets net8.0, net9.0 and net10.0.

A quick look

GetUser.cs
[Handler]
public sealed partial class GetUser
{
	public sealed record Query(int UserId);
	public sealed record Response(int UserId, string Name);

	private async ValueTask<Response> HandleAsync(
		Query query,
		UserRepository repository,
		CancellationToken token
	) => await repository.GetUser(query.UserId, token);
}

[CacheFor<GetUser>]
public sealed partial class GetUserCache
{
	protected override string TransformKey(GetUser.Query request) =>
		$"GetUser({request.UserId})";
}

Register the generated cache alongside your handlers, then inject GetUserCache and call it:

Program.cs
builder.Services.AddMemoryCache();
builder.Services.AddWebHandlers();
builder.Services.AddWebCaches();
var response = await cache.GetValue(new GetUser.Query(42), token);

Where to go next