New to Claude Skills? Learn how to install them →

Mgithub on GitHub

MVVM Toolkit DI

OfficialFree

Streamline ViewModel integration with Dependency Injection in .NET.

by github37.7k stars on github/awesome-copilot
2 views
Updated Aug 10, 2026
Get this skill

Free · Opens the source repo

What MVVM Toolkit DI does

The MVVM Toolkit DI skill enhances the integration of ViewModels from the CommunityToolkit.Mvvm with Microsoft.Extensions.DependencyInjection, a widely used dependency injection (DI) container in .NET applications. This skill is particularly useful for developers working with XAML-based applications such as WPF, WinUI 3, .NET MAUI, Uno, and Avalonia. By leveraging this skill, developers can effectively manage service lifetimes, resolve ViewModels, and ensure a clean architecture that adheres to the MVVM pattern.

At its core, this skill guides users through setting up a composition root using the .NET Generic Host. It emphasizes best practices such as constructor injection, which makes dependencies explicit and facilitates unit testing. The skill also covers various service lifetimes—Singleton, Transient, and Scoped—allowing developers to choose the appropriate lifetime for their services and ViewModels based on their application needs. This structured approach helps prevent common pitfalls associated with dependency management in XAML applications.

The skill also includes practical examples, such as how to wire up the IMessenger service for communication between ViewModels and how to resolve ViewModels in Views without relying on service locators. This not only simplifies the code but also enhances maintainability and testability. Furthermore, it provides insights into advanced features like keyed services for resolving different implementations of the same interface, which can be particularly beneficial in complex applications.

Overall, the MVVM Toolkit DI skill is an essential resource for developers looking to implement a robust dependency injection strategy in their .NET applications, ensuring that their MVVM architecture is clean, efficient, and easy to maintain.

When to use it

Use this skill when setting up a new XAML application or when you need to manage ViewModel lifetimes and dependencies effectively.

When not to use it

Avoid this skill if your application does not use MVVM or if you prefer to manage dependencies without a DI container.

What you can build with it

Setting Up a New XAML Application

When starting a new project, this skill helps establish a clean architecture by integrating ViewModels with a DI container.

Managing ViewModel Lifetimes

Use this skill to determine the appropriate lifetimes for your services and ViewModels, ensuring efficient resource management.

Testing ViewModels

The skill facilitates unit testing by promoting constructor injection, making it easier to swap dependencies with mocks.

How to install MVVM Toolkit DI

View source

1. Install with the skills CLI

npx skills add github/awesome-copilot/mvvm-toolkit-di --agent claude-code

2. Or install it manually

Download the skill folder and drop it into ~/.claude/skills/ for all projects, or .claude/skills/ to scope it to one repo. Restart Claude Code so it picks up the new skill.

Anthropic's agentic coding CLI, and the reference implementation of Agent Skills. Drop a skill folder into ~/.claude/skills and Claude Code loads it automatically whenever a task matches the skill's description. Claude Code docs

Inside SKILL.md

Written by github

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. Avoid Ioc.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 IMessenger once and injecting it into ObservableRecipient ViewModels
  • Resolving 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.json binding via Microsoft.Extensions.Configuration
  • Logging via Microsoft.Extensions.Logging
  • Hosted services (IHostedService) for background work
  • Scope 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

LifetimeMethodTypical use in XAML apps
SingletonAddSingleton<T>Shell/main-window VM, settings, file/HTTP services, the shared IMessenger, app-wide caches
TransientAddTransient<T>Per-page or per-document ViewModels (a fresh instance every resolve)
ScopedAddScoped<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

  1. Ioc.Default.GetService<T>() inside a VM constructor. Hides the dependency, breaks unit tests, prevents startup graph validation.
  2. Everything Singleton. A "per-document" VM registered as singleton becomes shared state across all documents — subtle data corruption. Use AddTransient for per-instance VMs.
  3. Multiple BuildServiceProvider() calls. Each call is a fresh container — singletons aren't shared. Build once at startup.
  4. Capturing IServiceProvider in long-lived objects. Indicates a service-locator pattern. Inject the specific dependencies you need.
  5. No scope validation in development. Use Host.CreateDefaultBuilder() (which sets ValidateScopes and ValidateOnBuild in development) so registration mistakes fail at startup, not at first use.
  6. 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

TopicFile
Full deep dive (Generic Host setup, lifetimes, keyed services, testing patterns, legacy Ioc)references/dependency-injection.md

External:

Frequently asked questions about MVVM Toolkit DI

Similar skills