Mvvm Toolkit Di
GitHubOfficialFirst committed by alvinashcraftDistributed by GitHub
- Skill
- Tool integration
- Software development
- MIT
- No issues found
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
This skill provides a comprehensive guide to wiring CommunityToolkit.Mvvm ViewModels into the Microsoft.Extensions.DependencyInjection container. It covers setting up the .NET Generic Host as a composition root, managing service lifetimes, implementing constructor injection, and handling advanced scenarios like keyed services and testing. It is designed for developers building XAML applications across WPF, WinUI 3, .NET MAUI, Uno, and Avalonia, emphasizing best practices to avoid service locator anti-patterns.
What it does
- Configures the .NET Generic Host as the primary composition root for XAML applications.
- Demonstrates constructor injection for ViewModels to ensure explicit dependency management.
- Explains how to manage Singleton, Transient, and Scoped service lifetimes.
- Provides patterns for resolving ViewModels in Views without coupling to service locators.
- Shows how to register and inject IMessenger for decoupled communication.
- Offers guidance on testing ViewModels by swapping dependencies via constructor injection.
When to use it
- When starting a new XAML application and needing a robust dependency injection setup.
- When you need to manage complex ViewModel dependencies and service lifetimes.
- When you want to improve testability by moving away from service locator patterns.
- When integrating logging, configuration, or background services into your MVVM application.
- When you need to resolve different implementations of the same interface using keyed services.
Advantages
- Promotes explicit dependency management through constructor injection.
- Enables easier unit testing by allowing direct injection of mocks.
- Leverages the standard .NET Generic Host for configuration and logging.
- Prevents runtime errors by validating the dependency graph at startup.
- Provides a consistent approach across multiple XAML frameworks.
Usage examples
- “How do I register my ViewModels and services in a .NET MAUI app?”
- The skill provides a template using Host.CreateDefaultBuilder() to register services and ViewModels in the ConfigureServices method, ensuring they are available for constructor injection.
- “How can I test a ViewModel that depends on an IFilesService?”
- The skill demonstrates using a mocking library to inject a mock IFilesService directly into the ViewModel constructor, avoiding the need to mock static service locators.
- “What is the best way to resolve a ViewModel in a Page?”
- The skill recommends resolving the ViewModel from the DI container in the Page's code-behind, allowing the container to handle all nested dependencies automatically.
Install
Download the skill as a ZIP:
https://mp-staging.autogineer.com/agent-skills/github/mvvm-toolkit-di/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip mvvm-toolkit-di.zip -d .agents/skills
Documentation by alvinashcraft
CommunityToolkit.Mvvm + Microsoft.Extensions.DependencyInjection
The MVVM Toolkit deliberately ships no DI container — it composes with
Microsoft.Extensions.DependencyInjection, the same container ASP.NET
Core, Worker services, and the .NET Generic Host use.
TL;DR. Build the service provider once at startup (prefer
Host.CreateDefaultBuilder()). Register services and ViewModels. Inject through constructors. AvoidIoc.Default.GetService<T>()in user code.
When to use this skill
Standing up the composition root for a new XAML app (WPF, WinUI 3, MAUI, Uno, Avalonia)
Choosing service/VM lifetimes
Wiring
IMessengeronce and injecting it intoObservableRecipientViewModelsResolving a page's ViewModel without coupling to a service locator
Diagnosing "Unable to resolve service for type X while attempting to activate Y"
For source generators and ViewModel patterns see the mvvm-toolkit
skill. For Messenger pub/sub see mvvm-toolkit-messenger.
Recommended composition root (Generic Host)
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using CommunityToolkit.Mvvm.Messaging;
public partial class App : Application
{
public IHost Host { get; }
public App()
{
Host = Microsoft.Extensions.Hosting.Host
.CreateDefaultBuilder()
.ConfigureServices((_, services) =>
{
services.AddSingleton<IFilesService, FilesService>();
services.AddSingleton<ISettingsService, SettingsService>();
services.AddSingleton<IMessenger>(WeakReferenceMessenger.Default);
services.AddSingleton<ShellViewModel>();
services.AddTransient<ContactViewModel>();
services.AddTransient<EditorViewModel>();
})
.Build();
}
public static T GetService<T>() where T : class =>
((App)Current).Host.Services.GetRequiredService<T>();
}Generic Host benefits:
appsettings.jsonbinding viaMicrosoft.Extensions.ConfigurationLogging via
Microsoft.Extensions.LoggingHosted services (
IHostedService) for background workScope validation in development builds
WPF and Windows Forms must integrate the host lifetime with the app lifetime — see Use the .NET Generic Host in a WPF app.
Without Generic Host
When you only need a service container and want zero extra dependencies:
var services = new ServiceCollection();
services.AddSingleton<IFilesService, FilesService>();
services.AddTransient<ContactViewModel>();
ServiceProvider provider = services.BuildServiceProvider();Constructor injection
Inject services and child ViewModels through the constructor:
public sealed partial class ContactViewModel(
IFilesService files,
IMessenger messenger,
ILogger<ContactViewModel> logger)
: ObservableRecipient(messenger)
{
[ObservableProperty]
private string? name;
[RelayCommand]
private async Task SaveAsync()
{
logger.LogInformation("Saving {Name}", Name);
await files.SaveAsync(Name!);
}
}Why constructor injection beats a service locator:
Dependencies are explicit and visible at the call site
Unit tests inject fakes/mocks directly
The DI container validates the dependency graph at startup
Missing registrations throw immediately, not at first use
Lifetimes
| Lifetime | Method | Typical use in XAML apps |
|---|---|---|
| Singleton | AddSingleton<T> | Shell/main-window VM, settings, file/HTTP services, the shared IMessenger, app-wide caches |
| Transient | AddTransient<T> | Per-page or per-document ViewModels (a fresh instance every resolve) |
| Scoped | AddScoped<T> | Rarely needed in client apps; useful with explicit IServiceScope (e.g., per-window scopes) |
services.AddSingleton<ShellViewModel>(); // 1 instance for app lifetime
services.AddTransient<NoteViewModel>(); // new instance per resolve
services.AddScoped<DialogService>(); // 1 per scope (rare)Resolving in a View
Resolve the page's root ViewModel in code-behind, then let it pull its own dependencies:
public sealed partial class ContactPage : Page
{
public ContactViewModel ViewModel { get; }
public ContactPage()
{
ViewModel = App.GetService<ContactViewModel>();
InitializeComponent();
}
}Bind in XAML with {x:Bind ViewModel.Xxx} (compiled bindings) or
{Binding Xxx} against DataContext.
For navigation frameworks (WinUI 3 Frame.Navigate, MAUI Shell, Prism,
MVVMCross), let the framework resolve the page and the page resolves its
ViewModel from DI. Don't new ViewModels manually.
IMessenger registration
Register the messenger you want once, inject IMessenger everywhere:
services.AddSingleton<IMessenger>(WeakReferenceMessenger.Default);
// or
services.AddSingleton<IMessenger>(StrongReferenceMessenger.Default);Then:
public sealed partial class MyViewModel(IMessenger messenger)
: ObservableRecipient(messenger) { }For per-window messengers, register with keyed services or as scoped instances and inject into per-window ViewModels.
See the mvvm-toolkit-messenger skill for the messenger surface area.
Keyed services (.NET 8+)
Resolve different implementations of the same interface by key:
services.AddKeyedSingleton<IExporter, CsvExporter>("csv");
services.AddKeyedSingleton<IExporter, JsonExporter>("json");
public sealed partial class ExportViewModel(
[FromKeyedServices("csv")] IExporter csvExporter,
[FromKeyedServices("json")] IExporter jsonExporter)
: ObservableObject { /* ... */ }Testing seams
Constructor-injected dependencies are trivial to swap in tests. With
Moq:
[Fact]
public async Task Save_calls_files_service()
{
var files = new Mock<IFilesService>();
var messenger = new WeakReferenceMessenger();
var logger = NullLogger<ContactViewModel>.Instance;
var vm = new ContactViewModel(files.Object, messenger, logger)
{
Name = "Ada"
};
await vm.SaveCommand.ExecuteAsync(null);
files.Verify(f => f.SaveAsync("Ada"), Times.Once);
}If you're mocking Ioc.Default or static state, the ViewModel is using a
service locator — refactor to constructor injection.
Legacy: Ioc.Default
CommunityToolkit.Mvvm.DependencyInjection.Ioc is an escape hatch for
cases where constructor injection is impossible — XAML-instantiated VMs
for design-time data, ValueConverters, control templates.
Ioc.Default.ConfigureServices(
new ServiceCollection()
.AddSingleton<IFilesService, FilesService>()
.AddTransient<ContactViewModel>()
.BuildServiceProvider());
var files = Ioc.Default.GetRequiredService<IFilesService>();Treat it as the last resort. Inside ViewModels, services, and any class the DI container can construct, prefer constructor injection.
Common pitfalls
Ioc.Default.GetService<T>()inside a VM constructor. Hides the dependency, breaks unit tests, prevents startup graph validation.Everything
Singleton. A "per-document" VM registered as singleton becomes shared state across all documents — subtle data corruption. UseAddTransientfor per-instance VMs.Multiple
BuildServiceProvider()calls. Each call is a fresh container — singletons aren't shared. Build once at startup.Capturing
IServiceProviderin long-lived objects. Indicates a service-locator pattern. Inject the specific dependencies you need.No scope validation in development. Use
Host.CreateDefaultBuilder()(which setsValidateScopesandValidateOnBuildin development) so registration mistakes fail at startup, not at first use.Resolving scoped services from the root provider. They're effectively promoted to singleton lifetime — the warning is silent without scope validation. Either change the lifetime or resolve from an explicit
IServiceScope.
References
| Topic | File |
|---|---|
| Full deep dive (Generic Host setup, lifetimes, keyed services, testing patterns, legacy Ioc) | references/dependency-injection.md |
External:
DI overview: https://learn.microsoft.com/en-us/dotnet/core/extensions/dependency-injection
DI usage: https://learn.microsoft.com/en-us/dotnet/core/extensions/dependency-injection-usage
MVVM Toolkit Ioc page: https://learn.microsoft.com/en-us/dotnet/communitytoolkit/mvvm/ioc
Generic Host: https://learn.microsoft.com/en-us/dotnet/core/extensions/generic-host
Files
- ATTRIBUTION.mdAdded by AutoGineer873 B
- LICENSELicence file added by AutoGineer1.0 KiB
- SKILL.md9.1 KiB
- references/dependency-injection.md8.0 KiB
Requirements and compatibility
Written for: GitHub Copilot
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Security
No issues found by our static scan· No issues found
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- First committed by
alvinashcraft
- Publisher
- GitHub (Official)
- Distributed by
- GitHub
- Source
- github/awesome-copilot · skills/mvvm-toolkit-di · commit 797337f
- Licence
- MIT License (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
- Contributors
- alvinashcraft
AutoGineer is not affiliated with or endorsed by alvinashcraft or GitHub.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download mvvm-toolkit-di.zip