Install any skill in seconds. Free to start, no credit card required.
Get Started Free →Wire CommunityToolkit.Mvvm ViewModels into Microsoft.Extensions.DependencyInjection. Covers the .NET Generic Host composition root, constructor injection, service lifetimes (Singleton / Transient / Scoped), IMessenger registration, resolving ViewModels in Views, keyed services, testing seams, and the legacy Ioc.Default escape hatch. Use across WPF, WinUI 3, .NET MAUI, Uno, and Avalonia.
.claude/skills/mvvm-toolkit-di/SKILL.md| Test case | Without → With | Effect | Δ tokens | Δ turns |
|---|---|---|---|---|
| case-06 | ✗→✓ | ▲ Improved | — | — |
| case-16 | ✗→✓ | ▲ Improved | — | — |
| case-01 | ✗→✓ | ▲ Improved | — | — |
| case-02 | ✗→✓ | ▲ Improved | — | — |
| case-03 | ✗→✓ | ▲ Improved | — | — |
Microsoft.Extensions.DependencyInjectionThe 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. Avoid Ioc.Default.GetService<T>() > in user code.
MAUI, Uno, Avalonia)
IMessenger once and injecting it into ObservableRecipientViewModels
activate Y"
For source generators and ViewModel patterns see the mvvm-toolkit skill. For Messenger pub/sub see mvvm-toolkit-messenger.
csharpusing 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.json binding via Microsoft.Extensions.ConfigurationMicrosoft.Extensions.LoggingIHostedService) for background work> WPF and Windows Forms must integrate the host lifetime with the app > lifetime — see > Use the .NET Generic Host in a WPF app.
When you only need a service container and want zero extra dependencies:
csharpvar services = new ServiceCollection(); services.AddSingleton<IFilesService, FilesService>(); services.AddTransient<ContactViewModel>(); ServiceProvider provider = services.BuildServiceProvider();
Inject services and child ViewModels through the constructor:
csharppublic 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:
| 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) |
csharpservices.AddSingleton<ShellViewModel>(); // 1 instance for app lifetime services.AddTransient<NoteViewModel>(); // new instance per resolve services.AddScoped<DialogService>(); // 1 per scope (rare)
Resolve the page's root ViewModel in code-behind, then let it pull its own dependencies:
csharppublic 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 registrationRegister the messenger you want once, inject IMessenger everywhere:
csharpservices.AddSingleton<IMessenger>(WeakReferenceMessenger.Default); // or services.AddSingleton<IMessenger>(StrongReferenceMessenger.Default);
Then:
csharppublic 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.
Resolve different implementations of the same interface by key:
csharpservices.AddKeyedSingleton<IExporter, CsvExporter>("csv"); services.AddKeyedSingleton<IExporter, JsonExporter>("json"); public sealed partial class ExportViewModel( [FromKeyedServices("csv")] IExporter csvExporter, [FromKeyedServices("json")] IExporter jsonExporter) : ObservableObject { /* ... */ }
Constructor-injected dependencies are trivial to swap in tests. With Moq:
csharp[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.
Ioc.DefaultCommunityToolkit.Mvvm.DependencyInjection.Ioc is an escape hatch for cases where constructor injection is impossible — XAML-instantiated VMs for design-time data, ValueConverters, control templates.
csharpIoc.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.
Ioc.Default.GetService<T>() inside a VM constructor. Hides thedependency, breaks unit tests, prevents startup graph validation.
Singleton. A "per-document" VM registered as singletonbecomes shared state across all documents — subtle data corruption. Use AddTransient for per-instance VMs.
BuildServiceProvider() calls. Each call is a freshcontainer — singletons aren't shared. Build once at startup.
IServiceProvider in long-lived objects. Indicates aservice-locator pattern. Inject the specific dependencies you need.
Host.CreateDefaultBuilder()(which sets ValidateScopes and ValidateOnBuild in development) so registration mistakes fail at startup, not at first use.
effectively promoted to singleton lifetime — the warning is silent without scope validation. Either change the lifetime or resolve from an explicit IServiceScope.
| Topic | File | |-------|------| | Full deep dive (Generic Host setup, lifetimes, keyed services, testing patterns, legacy Ioc) | references/dependency-injection.md |
External:
| Case | Status | Duration (ms) | Turns | Tokens | Tool calls | ||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Without | With | Δ | Without | With | Δ | Without | With | Δ | Without | With | Δ | ||
case-04 | fail→fail | — | — | — | — | — | — | — | — | — | — | — | — |
case-06 | fail→pass | — | — | — | — | — | — | — | — | — | — | — | — |
case-14 | fail→fail | — | — | — | — | — | — | — | — | — | — | — | — |
case-17 | fail→fail | — | — | — | — | — | — | — | — | — | — | — | — |
case-11 | fail→fail | — | — | — | — | — | — | — | — | — | — | — | — |
case-08 | fail→fail | — | — | — | — | — | — | — | — | — | — | — | — |
case-19 | fail→fail | — | — | — | — | — | — | — | — | — | — | — | — |
case-13 | fail→fail | — | — | — | — | — | — | — | — | — | — | — | — |
case-16 | fail→pass | — | — | — | — | — | — | — | — | — | — | — | — |
case-12 | fail→fail | — | — | — | — | — | — | — | — | — | — | — | — |
case-18 | fail→fail | — | — | — | — | — | — | — | — | — | — | — | — |
case-21 | fail→fail | — | — | — | — | — | — | — | — | — | — | — | — |
case-01 | fail→pass | — | — | — | — | — | — | — | — | — | — | — | — |
case-22 | fail→fail | — | — | — | — | — | — | — | — | — | — | — | — |
case-10 | fail→fail | — | — | — | — | — | — | — | — | — | — | — | — |
case-20 | fail→fail | — | — | — | — | — | — | — | — | — | — | — | — |
case-02 | fail→pass | — | — | — | — | — | — | — | — | — | — | — | — |
case-03 | fail→pass | — | — | — | — | — | — | — | — | — | — | — | — |
case-15 | fail→fail | — | — | — | — | — | — | — | — | — | — | — | — |
case-09 | fail→fail | — | — | — | — | — | — | — | — | — | — | — | — |
case-07 | fail→fail | — | — | — | — | — | — | — | — | — | — | — | — |
case-23 | fail→fail | — | — | — | — | — | — | — | — | — | — | — | — |
case-05 | fail→fail | — | — | — | — | — | — | — | — | — | — | — | — |
DecimalAI ran this skill against gemini-3.6-flash twice over the same eval suite — once with the skill loaded and once without — and compared the two runs case by case. 23 cases were attempted. The headline lift of +22 percentage points is the difference between those two pass rates over the 23 comparable cases.
The per-case answers from this run were removed by the retention sweep, so the case table below shows the verdicts without the text either arm produced. The counts above were recorded at the time and are unaffected. Answers are now kept for 180 days.
Other measured skills in the registry, with their headline benchmark lift.