/dotnet-desktop-development:mvvm-toolkit-messengerfrom dotnet-desktop-development
Configure CommunityToolkit.Mvvm Messenger pub/sub for decoupled ViewModel communication, covering weak/strong messengers, message types, channel tokens, and request/reply patterns.
Ships in dotnet-desktop-development. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
Configure CommunityToolkit.Mvvm messenger communication by choosing weak, strong, or scoped IMessenger instances, defining message types, and returning registration, send, token, request/reply, and lifecycle patterns for ViewModels.
Pub/sub messaging for ViewModels (or any objects) without forcing a shared
reference graph. Part of CommunityToolkit.Mvvm 8.x.
TL;DR. Default to
WeakReferenceMessenger.Default. Register handlers with the(recipient, message)lambda and thestaticmodifier so you never capturethis. Inherit fromObservableRecipientand toggleIsActiveat activation/deactivation to get automatic register/unregister.
For source generators, base classes, and commands see the mvvm-toolkit
skill. For DI wiring (registering an IMessenger instance), see
mvvm-toolkit-di.
| Type | When |
|---|---|
WeakReferenceMessenger.Default | Default. Recipients held weakly — eligible for GC even while registered. Internal trimming runs during full GCs; no manual Cleanup() needed. |
StrongReferenceMessenger.Default | Profiler shows the messenger is hot and allocation matters. Recipients are pinned until you Unregister. Forgetting unregistration leaks them. |
Custom IMessenger instance | Per-window/per-scope (e.g., one messenger per app window). Construct directly, inject via DI. |
ObservableRecipient's parameterless constructor uses
WeakReferenceMessenger.Default. Pass a different IMessenger to its
constructor to override.
The toolkit ships base classes; any class works.
using CommunityToolkit.Mvvm.Messaging.Messages;
// Single-payload broadcast
public sealed class LoggedInUserChangedMessage(User user)
: ValueChangedMessage<User>(user);
// Custom shape (records are great for this)
public sealed record ThemeChangedMessage(AppTheme NewTheme);
// Empty signal
public sealed record RefreshRequestedMessage;
WeakReferenceMessenger.Default.Register<MyViewModel, ThemeChangedMessage>(
this,
static (recipient, message) => recipient.OnThemeChanged(message.NewTheme));
The static modifier prevents accidental closure allocation and keeps
this out of the lambda — use the recipient parameter instead.
IRecipient<TMessage> interface stylepublic sealed class MyViewModel : ObservableRecipient,
IRecipient<ThemeChangedMessage>,
IRecipient<RefreshRequestedMessage>
{
public void Receive(ThemeChangedMessage message) { /* ... */ }
public void Receive(RefreshRequestedMessage message) { /* ... */ }
}
ObservableRecipient.OnActivated() calls Messenger.RegisterAll(this),
which subscribes every IRecipient<T> interface implemented by the type.
If you're not using ObservableRecipient, register manually:
WeakReferenceMessenger.Default.RegisterAll(this);
WeakReferenceMessenger.Default.Send(new ThemeChangedMessage(AppTheme.Dark));
// Empty payloads use the parameterless overload:
WeakReferenceMessenger.Default.Send<RefreshRequestedMessage>();
Scope messages to a sub-system or window with a token (any equatable
value — int, string, Guid):
const int LeftPaneChannel = 1;
WeakReferenceMessenger.Default.Register<MyViewModel, RefreshRequestedMessage, int>(
this, LeftPaneChannel,
static (r, _) => r.RefreshLeft());
WeakReferenceMessenger.Default.Send(new RefreshRequestedMessage(), LeftPaneChannel);
Messages sent without a token use the default shared channel — they are not delivered to channel-scoped recipients.
For ask-style scenarios where a recipient provides a value back to the
sender, use the RequestMessage<T> family.
public sealed class CurrentUserRequest : RequestMessage<User> { }
WeakReferenceMessenger.Default.Register<UserService, CurrentUserRequest>(
this,
static (r, m) => m.Reply(r.CurrentUser));
User user = WeakReferenceMessenger.Default.Send<CurrentUserRequest>();
The implicit conversion from CurrentUserRequest to User throws if no
recipient called Reply. Capture the message to check first:
var request = WeakReferenceMessenger.Default.Send<CurrentUserRequest>();
if (request.HasReceivedResponse)
User user = request.Response;
public sealed class CurrentUserRequest : AsyncRequestMessage<User> { }
WeakReferenceMessenger.Default.Register<UserService, CurrentUserRequest>(
this,
static (r, m) => m.Reply(r.GetCurrentUserAsync()));
User user = await WeakReferenceMessenger.Default.Send<CurrentUserRequest>();
CollectionRequestMessage<T> and AsyncCollectionRequestMessage<T> collect
a Reply from every responding recipient:
public sealed class OpenDocumentsRequest : CollectionRequestMessage<Document> { }
var docs = WeakReferenceMessenger.Default.Send<OpenDocumentsRequest>();
foreach (Document doc in docs) { /* ... */ }
Even with WeakReferenceMessenger, unregister explicitly when a recipient
is being torn down — it trims dead entries and improves performance:
WeakReferenceMessenger.Default.Unregister<ThemeChangedMessage>(this);
WeakReferenceMessenger.Default.Unregister<ThemeChangedMessage, int>(this, LeftPaneChannel);
WeakReferenceMessenger.Default.UnregisterAll(this);
ObservableRecipient.OnDeactivated() does this automatically when
IsActive flips to false. Set it from your activation hook:
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
ViewModel.IsActive = true;
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
ViewModel.IsActive = false;
base.OnNavigatedFrom(e);
}
this in the lambda. (r, m) => OnX(m) implicitly
captures this; allocates a closure and confuses lifetime. Always use
(r, m) => r.OnX(m) with static.Unregister. With
StrongReferenceMessenger, recipients (and their entire object graph)
stay pinned forever. Either inherit from ObservableRecipient
(auto-unregisters in OnDeactivated) or call UnregisterAll(this).BaseMessage is
not invoked for DerivedMessage : BaseMessage. Register each
concrete type.WeakReferenceMessenger.Default
and registering via an injected per-window messenger means the message
never arrives. Use the same IMessenger everywhere (typically inject
it via ObservableRecipient(messenger)).OnActivated never runs. ObservableRecipient only registers
IRecipient<T> handlers when IsActive flips from false to true.DispatcherQueue.TryEnqueue / Dispatcher.BeginInvoke).services.AddSingleton<IMessenger>(WeakReferenceMessenger.Default); // app-wide
services.AddScoped<WindowScopedMessenger>(); // per-window
Inject the appropriate IMessenger into the ViewModel constructor:
public sealed partial class WindowViewModel(IMessenger messenger)
: ObservableRecipient(messenger) { }
This isolates broadcasts to a single window — useful for multi-window desktop apps (WinUI 3, WPF, MAUI desktop, Avalonia).
| Topic | File |
|---|---|
| Full deep dive (more channel/lifecycle examples, diagnostics) | references/messenger-patterns.md |
## MVVM Toolkit messenger result
**Status:** implemented | guidance only | blocked
**Messenger:** `WeakReferenceMessenger.Default` | `StrongReferenceMessenger.Default` | custom `IMessenger`
**Message types:** `<messages defined or reviewed>`
### Pattern
- Registration: `<Register<TRecipient,TMessage> or RegisterAll>`
- Sending: `<Send(...)>`
- Scope: default channel | token `<token>`
- Lifecycle: `ObservableRecipient.IsActive` | manual `UnregisterAll(this)`
### Validation
- Static handler lambda: pass | fail
- Same messenger instance used for send and receive: pass | fail
- UI dispatch handled for UI updates: pass | fail
WeakReferenceMessenger.Default is used by default unless profiling or scoping justifies another IMessenger.static (recipient, message) and avoid capturing this.StrongReferenceMessenger recipients unregister through ObservableRecipient.OnDeactivated() or UnregisterAll(this).HasReceivedResponse before reading Response when no response is possible.DispatcherQueue.TryEnqueue or Dispatcher.BeginInvoke.External:
WeakReferenceMessenger API: https://learn.microsoft.com/en-us/dotnet/api/communitytoolkit.mvvm.messaging.weakreferencemessengerWhat SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
mvvm-toolkit, messenger, viewmodel-communication, pub-sub, dotnet
npx claudepluginhub gbb-acelerators/awesome-harness-primitives --plugin dotnet-desktop-development9 skills in this plugin
/dotnet-timezoneResolve .NET and C# timezone questions with TimeZoneInfo, DateTimeOffset, TimeZoneConverter, NodaTime, UTC conversion, daylight saving time, scheduling, Windows and IANA timezone IDs, location lookup, and copy-paste-ready code. Use this skill when a .NET user needs the timezone for a city, address, region, or country, or asks about cross-platform timezone handling./msstore-cliUse Microsoft Store Developer CLI (msstore) to configure Partner Center credentials, list Store apps, package and publish Windows submissions, check status, manage package flights, gradual rollouts, and CI/CD publishing for Windows App SDK/WinUI, UWP, .NET MAUI, Flutter, Electron, React Native, and PWA apps. Use when asked to configure Store credentials, publish to Microsoft Store, check submission status, or automate Store releases./mvvm-toolkitCommunityToolkit.Mvvm core guidance for ViewModels, source generators, observable properties, commands, validation, and base-class selection. Use this skill when authoring or reviewing code that uses CommunityToolkit.Mvvm 8.x, ObservableObject, ObservableValidator, ObservableRecipient, ObservableProperty, RelayCommand, AsyncRelayCommand, NotifyPropertyChangedFor, NotifyCanExecuteChangedFor, or NotifyDataErrorInfo across WPF, WinUI 3, MAUI, Uno, and Avalonia./mvvm-toolkit-diWire CommunityToolkit.Mvvm ViewModels into Microsoft.Extensions.DependencyInjection for XAML apps. Use this skill when standing up a .NET Generic Host composition root for WPF, WinUI 3, .NET MAUI, Uno, or Avalonia; choosing Singleton, Transient, or Scoped lifetimes; registering IMessenger; resolving ViewModels in Views; using keyed services; adding test seams; or replacing legacy Ioc.Default service-locator code./nuget-managerManage NuGet packages safely in .NET projects and solutions using the `dotnet` CLI. Use this skill when adding, removing, or updating package versions, verifying `PACKAGE_NAME` availability, working with `Directory.Packages.props`, or deciding when direct `.csproj` edits are allowed./system-commandline-cliAdd, modify, or review .NET CLI commands built with System.CommandLine by applying project command-base conventions, options and arguments, SetAction handlers, RootCommand registration, global options, dependency injection, validation, naming, and destructive-operation confirmation. Use when the user mentions System.CommandLine, CommandBase, ParseResult, SetAction, RootCommand, subcommands, or asks to add a CLI verb.Other plugins' skills for the same job