shinyorg/mediator/shiny-mediator-2

Claude Code and agent skill by shinyorg/mediator

Trust tier 3
  • community
Source check pending

Checking that the SKILL.md file is still in the repository.

Generate Shiny Mediator handlers, contracts, middleware, and scaffold projects for .NET applications

Install

npx vskill@latest install shinyorg/mediator/shiny-mediator-2

SKILL.md

Shiny Mediator Skill

You are an expert in Shiny Mediator, a mediator pattern library for .NET applications.

When to Use This Skill

Invoke this skill when the user wants to:

  • Create request handlers, command handlers, event handlers, or stream handlers
  • Generate contracts (IRequest, ICommand, IEvent, IStreamRequest)
  • Add middleware (caching, resilience, validation, offline)
  • Scaffold ASP.NET, MAUI, Blazor, Uno Platform, or Avalonia projects with Shiny Mediator
  • Configure Shiny Mediator in their application
  • Set up ASP.NET Server-Sent Events (SSE) endpoints with stream handlers
  • Use event subscriptions (WaitForSingleEvent, EventStream, Subscribe)
  • Generate strongly-typed HTTP clients from OpenAPI/Swagger specs
  • Create contract-first HTTP request handlers with [Get], [Post], etc.
  • Expose mediator contracts as AI tools via Microsoft.Extensions.AI
  • Expose mediator requests/commands to Siri, Shortcuts, Apple Intelligence or Android AppFunctions (Gemini) via Shiny.Mediator.AppFunctions
  • Migrate from MediatR to Shiny Mediator

Library Overview

Documentation: https://shinylib.net/mediator

Shiny Mediator is AOT & trimming friendly, using source generators for automatic DI registration.

Core Patterns
PatternContractHandlerUsage
RequestIRequest<TResult>IRequestHandler<TRequest, TResult>Queries returning data
CommandICommandICommandHandler<TCommand>Void state changes
EventIEventIEventHandler<TEvent>Pub/sub notifications
StreamIStreamRequest<TResult>IStreamRequestHandler<TRequest, TResult>IAsyncEnumerable
Handler Registration

Always use registration attributes:

csharp
[MediatorSingleton] // Stateless handlers
[MediatorScoped] // Handlers needing per-request services (DbContext)

Critical: Partial Class Requirement

When using any middleware attribute ([Cache], [OfflineAvailable], [Resilient], [MainThread], [TimerRefresh], [Sample], [Throttle]), the handler class must be declared as `partial`:

csharp
[MediatorSingleton]
public partial class MyHandler : IRequestHandler<MyRequest, MyResult> // partial required!
{
[Cache(AbsoluteExpirationSeconds = 60)]
public Task<MyResult> Handle(...) { }
}

This enables the source generator to create the IHandlerAttributeMarker implementation. Without partial, you'll get error SHINY001.

Basic Setup

ASP.NET:

csharp
builder.Services.AddShinyMediator(x => x
.AddMediatorRegistry()
);
app.MapGeneratedMediatorEndpoints();

MAUI:

csharp
builder.AddShinyMediator(x => x
.AddMediatorRegistry()
.UseMaui()
.AddMauiPersistentCache()
.PreventEventExceptions()
);

Blazor:

csharp
builder.Services.AddShinyMediator(x => x
.AddMediatorRegistry()
.UseBlazor()
.PreventEventExceptions()
);

Uno Platform (App.xaml.cs, Uno.Extensions hosting - the IApplicationBuilder overload tracks builder.Window):

csharp
var builder = this.CreateBuilder(args)
.AddShinyMediator(x => x
.AddMediatorRegistry()
.AddUnoPersistentCache()
);
// without Uno.Extensions hosting: services.AddShinyMediator(x => x.UseUno(MainWindow));

Avalonia (App.axaml.cs, wherever the ServiceCollection is built - windows/main view are found via ApplicationLifetime, nothing to pass):

csharp
services.AddShinyMediator(x => x
.AddMediatorRegistry()
.UseAvalonia()
.AddAvaloniaPersistentCache()
);

UI event collectors (MAUI, Blazor, Uno, Avalonia): pages/views and their view models (BindingContext / DataContext) that implement IEventHandler<T> receive published events automatically. Never register those views or view models as event handlers in DI - that creates new instances instead of reaching the one on screen.

Logging & Configuration are optional (v6.8+) - do NOT tell users they must call AddLogging() or register an IConfiguration to use the mediator. Every built-in service and middleware injects ILogger / ILoggerFactory / IConfiguration as an optional constructor argument defaulting to null. With no logging registered, log statements are skipped. With no IConfiguration registered, every configuration section (Cache, Offline, ReplayStream, Resilience, TimerRefresh, PerformanceLogging, UserErrorNotifications, Http) resolves to "not configured" and the middleware passes through - use the attribute equivalents ([Cache], [OfflineAvailable], [TimerRefresh], [Resilient]) when there is no configuration source.

Application-level handlers and middleware can still inject ILogger / IConfiguration as required dependencies - the app controls its own container. Follow the optional convention (ILogger<T>? logger = null last in the constructor, logger?.LogDebug(...)) when writing middleware or infrastructure meant to ship in a reusable library.

JSON Serialization (v6.6+)

Mediator uses Shiny.ISerializer from Shiny.Extensions.Serialization. The default chain is AOT-strict — no reflection fallback — so every contract that touches JSON (HTTP transport, storage cache, offline service, TickerQ scheduled commands, ASP.NET endpoints) must be in a registered JsonSerializerContext. Missing registrations throw InvalidOperationException: No JsonTypeInfo registered for type 'T' at runtime; the compiler won't catch it.

Default pattern when generating contracts. Always emit a [ShinyJsonContext]-tagged partial JsonSerializerContext alongside the contracts and list every request, response, event, and scheduled-command type:

csharp
using System.Text.Json.Serialization;
using Shiny;
[ShinyJsonContext]
[JsonSerializable(typeof(GetCustomerRequest))]
[JsonSerializable(typeof(CustomerResponse))]
[JsonSerializable(typeof(OrderPlacedEvent))]
internal partial class AppJsonContext : JsonSerializerContext;

The [ModuleInitializer] emitted by the extensions generator registers this context with Shiny.Json before Main runs — no services.AddJsonContext(...) call needed.

Opt-in auto-generation (default off). Setting <ShinyMediatorGenerateJsonContext>true</ShinyMediatorGenerateJsonContext> in the project file makes the mediator source generator emit a per-assembly __ShinyMediatorContractsJsonResolver covering every registered handler's request, response, command, event, and stream contract types (transitively, including their public property types), plus a [ModuleInitializer] that registers it. When enabled you don't need to hand-declare a [ShinyJsonContext] for in-assembly handler contracts. It is opt-in so there's always an escape hatch if the generated resolver misbehaves — when generating contracts, keep emitting an explicit [ShinyJsonContext] as the default unless the consumer has turned this property on. Cross-assembly contract types still need registration in their owning assembly.

Contract Keys & Trimming

Caching, offline, replay, and the HTTP cache key contracts through IContractKeyProvider. The default DefaultContractKeyProvider resolves keys in this order: IContractKey on the contract, then any registered IContractKeySource, then reflection over the public properties. The reflection path carries [RequiresUnreferencedCode], so trimmed and AOT apps get an IL2026 warning when it's reachable.

  • Trimmed/AOT apps or trim warnings (`IL2026`/`IL2075` from `DefaultContractKeyProvider`): set

<ShinyMediatorGenerateContractKeys>true</ShinyMediatorGenerateContractKeys> in the app project. The generator emits a reflection-free IContractKeySource for every contract declared in the project and every contract its [MediatorSingleton]/[MediatorScoped] handlers use. AddMediatorRegistry() registers it. Keys keep the reflection format, so existing cache/offline entries still match. It also defaults ShinyMediatorReflectionContractKeys to false, which trims the reflection fallback away. An uncovered contract then throws InvalidOperationException; fix it with IContractKey, [ContractKey], or <ShinyMediatorReflectionContractKeys>true</ShinyMediatorReflectionContractKeys>.

  • It's opt-in (default off). Don't add it unless the consumer trims, publishes AOT, or asks for it.
  • A custom provider: cfg.SetContractKeyProvider<T>() replaces the default whether you call it before or after AddShinyMediator.
  • AddDataAnnotations() is [RequiresUnreferencedCode]. For trimmed/AOT apps, prefer FluentValidation or hand-written validation.
  • Native AOT: register handlers with [MediatorSingleton]/[MediatorScoped] so the generated executor dispatches them. Hand-registered handlers fall back to a MakeGenericType-based executor.
  • Native AOT: HTTP/OpenAPI generated handlers come with their own generated executor (registered by their registration method), so no extra setup is needed for them.
  • Native AOT: don't use value types as a contract or result (IRequest<bool>, IRequest<SomeEnum>, record struct commands). MS.DI can't close open-generic middleware over a value type under AOT, so the first call throws once any open middleware (performance logging, caching, offline, main thread…) is registered. The generator reports warning SHINYMED010 when PublishAot or IsAotCompatible is set. Default to a reference type, e.g. public record IsOpenResult(bool Value); with IRequest<IsOpenResult>.

Collections (`List<T>`, `T[]`, `IAsyncEnumerable<T>`, etc.) of a contract type. Mark the element type with [ShinyJsonInclude]:

csharp
[ShinyJsonInclude]
public partial class Customer { /* ... */ }

OpenAPI HTTP clients with `GenerateJsonConverters="true"`: the OpenAPI generator emits a custom IJsonTypeInfoResolver covering every generated model + contract + enum (including Nullable<TEnum>), every scalar the generated code touches (Guid, DateOnly, T?…) and List<T> / T[] / Dictionary<string, V> shapes at any depth, plus a [ModuleInitializer]. Converters on JsonSerializerOptions.Converters still win for scalars. Users don't need [ShinyJsonContext] for OpenAPI-generated types, and the generated converters are free of IL2026/IL3050 warnings.

Attribute-driven HTTP clients (`[Get]` / `[Post]` / `[Body]`): user-written types; require explicit [ShinyJsonContext] registration.

Migration from v5/early-v6:

  • ISerializerService was removed — replace with Shiny.ISerializer (Shiny namespace, from

Shiny.Extensions.Serialization).

  • SysTextJsonSerializerService was removed — DI registration is automatic via AddShinyMediator.
  • ShinyMediatorBuilder.SetSerializer<T>() was removed — replace by either registering a different

Shiny.ISerializer in DI before AddShinyMediator, or calling Shiny.Json.AddContext / Shiny.Json.AddResolver.

  • The legacy [SourceGenerateJsonConverter] attribute still works for backward compatibility but

new code should use [ShinyJsonContext] + [JsonSerializable] instead — it gives first-class AOT coverage of collection shapes.

Tests / development scenarios that need reflection fallback (ad-hoc / anonymous types):

csharp
// In an [assembly: ...] or a [ModuleInitializer]
Shiny.Json.AddResolver(new System.Text.Json.Serialization.Metadata.DefaultJsonTypeInfoResolver());

This is not AOT-safe — use only in test fixtures or non-production code.

Code Generation Instructions

When generating Shiny Mediator code:

1. Contracts

Always use records for immutability:

csharp
public record GetUserRequest(int UserId) : IRequest<UserDto>;
public record CreateUserCommand(string Name, string Email) : ICommand;
public record UserCreatedEvent(int UserId, string Name) : IEvent;
2. Handlers

This is the start of the file. Read the full SKILL.md on GitHub.

Security

  • Security scanPassed, 95 of 100Pattern checks on the skill's files.
  • Model reviewPassed

Quality evaluation

  • Task evaluationNot runNo evaluation yet. Run one in Skill Studio.

Source

Popularity

Repository stars
42
Repository forks
5
7-day trend score
19

Stars and forks are for the whole GitHub repository, not this skill alone. Refreshed 17 Mar 2026, 8 months ago.

Works with

Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.

  • Claude Code
  • Cursor
  • GitHub Copilot
  • Windsurf
  • Codex
  • Gemini CLI
  • Cline
  • Amp
  • Roo Code
  • Goose
  • Continue
  • Kilo Code
  • Junie
  • Trae
  • OpenHands
  • Qwen Code
  • AI Agent
  • Tabnine Chat
  • Sourcegraph Cody
  • Amazon Q
  • Firebase Genkit
  • Sweep
  • Devin
  • Phind
  • Mentat
  • Claude Desktop
  • Aider
  • GPT Pilot
  • Plandex
  • bolt.new
  • v0
  • Replit Agent
  • Anse
  • TypingMind
  • BetterChatGPT
  • LibreChat
  • Warp AI
  • Pieces
  • Fig AI
Embed badge
vskill VERIFIED badge
[![vskill VERIFIED](https://verified-skill.com/api/v1/skills/shinyorg/mediator/shiny-mediator-2/badge)](https://verified-skill.com/skills/shinyorg/mediator/shiny-mediator-2)

Something wrong with this skill or its page? Tell us.