Tooark.Mediator.Caching 5.0.0

dotnet add package Tooark.Mediator.Caching --version 5.0.0
                    
NuGet\Install-Package Tooark.Mediator.Caching -Version 5.0.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Tooark.Mediator.Caching" Version="5.0.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Tooark.Mediator.Caching" Version="5.0.0" />
                    
Directory.Packages.props
<PackageReference Include="Tooark.Mediator.Caching" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Tooark.Mediator.Caching --version 5.0.0
                    
#r "nuget: Tooark.Mediator.Caching, 5.0.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Tooark.Mediator.Caching@5.0.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Tooark.Mediator.Caching&version=5.0.0
                    
Install as a Cake Addin
#tool nuget:?package=Tooark.Mediator.Caching&version=5.0.0
                    
Install as a Cake Tool

Tooark.Mediator.Caching

Library that caches Tooark.Mediator queries and removes the keys and tags declared by the commands after the outermost commit.

A query declares its cache key; a command declares the keys and tags it changes. The package puts two behaviors in the Tooark.Mediator pipeline, over the cache of Tooark.Caching: the handlers do not touch the cache, and the removal happens once, after the unit of work of Tooark.Mediator.EntityFrameworkCore is committed β€” never before, and never on a rollback.

πŸ“– Docs: Tooark.Mediator.Caching on the site Β· All packages Β· API reference

🌍 Languages: πŸ‡ΊπŸ‡Έ English (this file) Β· πŸ‡§πŸ‡· PortuguΓͺs


πŸ“‘ Contents


πŸ“– Overview

Piece What it does
ICachedQuery<T> A query whose response is cached under the key it declares
ICacheInvalidatingCommand<T> A command that removes keys and tags from the cache once it is done and committed
ICacheInvalidatingCommand The same, without a response (Unit)
AddTooarkMediatorCaching Adds both behaviors to the pipeline, at the position where it is called
  • Queries: the first run calls the handler and caches the response; the next ones return it without the handler, until the duration ends or a command removes the key. Simultaneous calls for the same key run the handler once.
  • "Not found": a null response is cached as "not found", for the short negative duration.
  • Commands: the keys and tags are removed once, after the outermost command is committed. Nested commands add their own; when the outermost command fails, nothing is removed.
  • Queries inside a command do not use the cache: they may see changes of the command not yet committed.

The package is not part of the Tooark aggregator, like Tooark.Caching, which it depends on. Install it on its own.


πŸ”§ Installation

dotnet add package Tooark.Mediator.Caching

βš™οΈ Configuration

using Tooark.Caching.Injections;
using Tooark.Mediator.Caching.Injections;
using Tooark.Mediator.EntityFrameworkCore.Injections;
using Tooark.Mediator.Injections;

builder.Services.AddTooarkCache(builder.Configuration);              // "Cache": { "DefaultDurationSeconds": 300 }

builder.Services.AddTooarkMediator(typeof(Program).Assembly);
builder.Services.AddTooarkMediatorBehavior(typeof(ValidationBehavior<,>));
builder.Services.AddTooarkMediatorCaching();                         // after validation, before the unit of work
builder.Services.AddTooarkMediatorUnitOfWork<AppDbContext>();

Registration order. The behaviors run in registration order, from the outermost to the innermost:

  1. Validation and authorization first. A cache hit returns the response without calling the next steps: a behavior registered after the cache does not run on a hit.
  2. The cache before the unit of work. The invalidation must wrap the unit of work to run after its commit. Called after AddTooarkMediatorUnitOfWork, AddTooarkMediatorCaching throws Mediator.Caching.RegisteredAfterUnitOfWork at registration.
Registration What it registers
AddTooarkMediatorCaching() The cache behavior (queries), the invalidation behavior (commands) and the scoped control of commands

It requires AddTooarkCache before (Cache.NotRegistered;AddTooarkMediatorCaching otherwise). The cache options β€” default duration, negative duration, fail-safe, tenant isolation, distributed level β€” come from Tooark.Caching and, with a server, Tooark.Caching.Distributed. Calling it again does not stack another behavior.


πŸ’Ύ Cached Queries

using Microsoft.EntityFrameworkCore;
using Tooark.Caching;
using Tooark.Mediator.Caching;
using Tooark.Mediator.Handlers;

public sealed record GetProduct(Guid Id) : ICachedQuery<ProductDto?>
{
  public string CacheKey => $"product:{Id}";

  public CacheEntryOptions? CacheOptions => Options;

  private static readonly CacheEntryOptions Options = new() { Duration = TimeSpan.FromMinutes(10), Tags = ["products"] };
}

public sealed class GetProductHandler(AppDbContext context) : IQueryHandler<GetProduct, ProductDto?>
{
  public Task<ProductDto?> HandleAsync(GetProduct request, CancellationToken cancellationToken = default) =>
    context.Products
      .Where(product => product.Id == request.Id)
      .Select(product => new ProductDto(product.Id, product.Name))
      .SingleOrDefaultAsync(cancellationToken);
}
Member Default Description
CacheKey (required) The key of the response, without the tenant. Put in it everything that changes the response
CacheOptions the cache options, without the eager refresh Duration, negative duration, tags and scope of the entry (CacheEntryOptions of Tooark.Caching)
  • Key: two queries with the same key get the same response. Include every parameter that changes it ($"products:page:{Page}:{Size}"). A blank key fails with Cache.KeyRequired.
  • null is "not found": a null response is cached for the negative duration (CacheEntryOptions.NegativeDuration or Cache:NegativeDurationSeconds), so lookups for a missing id stop reaching the database. A handler that throws β€” NotFoundException β€” caches nothing, and every call runs the handler.
  • Tenant: with tenant isolation, each tenant has its own response; without a current tenant, the query runs the handler and caches nothing. Data of no tenant uses Scope = ECacheScope.Shared. See the tenant rule.
  • Eager refresh: off for the queries unless CacheOptions sets EagerRefresh = true. The background refresh runs the handler after the request ended, when its DbContext is already disposed: turn it on only for a handler that does not depend on the request's scope.
  • Fail-safe: applies as in Tooark.Caching. A TooarkException 4xx from the handler (except 408 and 429) is an answer: it reaches the caller and drops the expired response.

🧹 Invalidation After the Commit

public sealed record RenameProduct(Guid Id, string Name) : ICacheInvalidatingCommand
{
  public IReadOnlyCollection<string>? InvalidatedCacheKeys => [$"product:{Id}"];

  public IReadOnlyCollection<string>? InvalidatedCacheTags => ["products"];
}

public sealed class RenameProductHandler(AppDbContext context) : ICommandHandler<RenameProduct>
{
  public async Task<Unit> HandleAsync(RenameProduct request, CancellationToken cancellationToken = default)
  {
    var product = await context.Products.SingleAsync(product => product.Id == request.Id, cancellationToken);

    product.Rename(request.Name);

    // No SaveChanges and no cache: the unit of work persists, and the invalidation removes after the commit
    return Unit.Value;
  }
}
Member Default Description
InvalidatedCacheKeys none Keys to remove, the same CacheKey of the queries
InvalidatedCacheTags none Tags to remove: every response with the tag leaves the cache
InvalidationScope ECacheScope.Tenant Tenant: the entries of the current tenant. Shared: the shared ones

How it runs:

  1. When the command starts, the keys and tags are read and checked. A blank key or tag (Cache.KeyRequired, Cache.TagRequired), or the Tenant scope with tenant isolation and no current tenant (Cache.Tenant.NotResolved), fails before the handler, and not after the commit.
  2. A command dispatched from inside another one adds its keys to the pending list; a key repeated by two commands, or by a new attempt of the transaction, is kept once.
  3. When the outermost command returns without an exception, the unit of work has already committed (it runs inside this behavior), and the keys and tags are removed once β€” in memory, in the distributed level and, with the backplane, in the other instances.
  4. When the outermost command fails, nothing is removed: the rollback did not change the data. A nested command that fails and is caught by the outer one keeps its keys pending: the unit of work of the outer command still saves what the nested one changed.

The removal uses no cancellation: the data is committed, and the cache must follow it even if the caller gives up. Commands without ICacheInvalidatingCommand also go through the behavior, which needs to know when the outermost command ends; they remove nothing.


🧠 Semantics

  • The invalidation narrows the window; the duration closes it. A query that started before the commit can store the old response after the removal: it read the old row, the command committed and removed the key, and only then the query stored what it had read. The duration of the entry bounds how long that response stays: choose it as the limit of how stale the data may get.
  • Committed but failed afterwards. The removal runs only when the outermost command completes without an exception. A failure after the unit of work committed β€” in a behavior registered between the cache and the unit of work, for instance β€” leaves the data committed and the old response in the cache until it expires.
  • Queries inside a command read the source. They see the changes of the command not yet committed (a tracked entity comes back already changed), which a rollback would undo, so they do not read nor write the cache. "Inside" follows the call chain: a query running beside a command in the same scope, not dispatched by it, uses the cache.
  • Simultaneous commands. The control of the commands follows the call chain. A command dispatched from inside another one, in the same scope, adds its removals to the outermost. Two commands running side by side in the same scope (the handlers of a notification with ParallelWhenAll, for instance) each remove after their own end. A command dispatched through another scope removes after its own end. The unit of work of Tooark.Mediator.EntityFrameworkCore still assumes one dispatch at a time per scope: with it registered, do not dispatch commands in parallel in the same scope.
  • Responses are shared. In memory, every caller gets the same instance: return immutable DTOs, never tracked entities. With the distributed level, the response must make the round trip through System.Text.Json.

πŸ“ Usage Examples

Query and command with tags

public sealed record ListProducts(int Page) : ICachedQuery<IReadOnlyList<ProductDto>>
{
  public string CacheKey => $"products:page:{Page}";

  public CacheEntryOptions? CacheOptions => Options;

  private static readonly CacheEntryOptions Options = new() { Tags = ["products"] };
}

public sealed record CreateProduct(string Name) : ICacheInvalidatingCommand<Guid>
{
  // Every page of the list: the new product changes them all
  public IReadOnlyCollection<string>? InvalidatedCacheTags => ["products"];
}

Shared reference data

public sealed record ListCountries : ICachedQuery<IReadOnlyList<CountryDto>>
{
  public string CacheKey => "countries";

  public CacheEntryOptions? CacheOptions => Options;

  // Data of no tenant: one copy for every tenant, also for anonymous requests
  private static readonly CacheEntryOptions Options = new() { Duration = TimeSpan.FromHours(12), Scope = ECacheScope.Shared };
}

public sealed record RenameCountry(string Code, string Name) : ICacheInvalidatingCommand
{
  public IReadOnlyCollection<string>? InvalidatedCacheKeys => ["countries"];

  public ECacheScope InvalidationScope => ECacheScope.Shared;
}

With Valkey or Redis

Nothing changes in the queries and commands: register the distributed level and every instance shares the responses, and a removal reaches them all through the backplane.

builder.Services.AddTooarkCache(builder.Configuration);
builder.Services.AddTooarkCacheDistributed(builder.Configuration);   // "Cache:Distributed"

builder.Services.AddTooarkMediator(typeof(Program).Assembly);
builder.Services.AddTooarkMediatorCaching();
builder.Services.AddTooarkMediatorUnitOfWork<AppDbContext>(EUnitOfWorkStrategy.Transaction);

πŸ“‹ Dependencies

Package Version Description
Tooark.Caching 5.x The cache
Tooark.Mediator 5.x Behavior pipeline and registration
Tooark.Mediator.Abstractions 5.x Message contracts (IQuery, ICommand)
Tooark.Exceptions 5.x Configuration and usage errors
Microsoft.Extensions.DependencyInjection.Abstractions 10.x Container registration

Tooark.Mediator.EntityFrameworkCore is not a dependency: the invalidation works without it (after the outermost command completes) and, with it, after its commit.


⚠️ Error Codes and Solutions

Message When Description Solution
Cache.NotRegistered;AddTooarkMediatorCaching Registration AddTooarkCache was not called before Call AddTooarkCache first
Mediator.Caching.RegisteredAfterUnitOfWork Registration AddTooarkMediatorUnitOfWork was called before AddTooarkMediatorCaching Call AddTooarkMediatorCaching before the unit of work
Mediator.Null.Service Registration The service collection is null Pass the service collection
Cache.KeyRequired Query or command Blank CacheKey or blank key in InvalidatedCacheKeys Build the key from the parameters
Cache.TagRequired Command, before handler Blank tag in InvalidatedCacheTags Leave the blank tag out
Cache.Tenant.NotResolved Command, before handler Invalidation in the Tenant scope without a current tenant Set the tenant of the scope, or use the Shared scope

The other messages of the cache are in Tooark.Caching.


🀝 Contributing

Contributions are welcome! Start with CONTRIBUTING.md β€” it covers the development workflow, the coding and commit conventions and the pull request checklist. Bugs and feature requests go through the issue templates of the Tooark repository.

By participating you agree to the Code of Conduct.


πŸ†˜ Help & Security

  • ❓ Questions, bugs, feature ideas β€” see SUPPORT.md for the right channel
  • πŸ”’ Security vulnerabilities β€” do not open a public issue; follow SECURITY.md

πŸ’– Support

If Tooark helps your projects, consider supporting its development:

Every contribution helps keep the project maintained and improving. Thank you! πŸ™


πŸ“„ License

This project is licensed under the BSD 3-Clause License.

Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
5.0.0 0 12/1/2026