← 返回列表
全部 Skill›测试与安全 Testing & Security›mvvm-toolkit-di

mvvm-toolkit-di

作者 @github · 语言 en
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.
测试与安全 Testing & Security测试通用访问网络待翻译
最近源活动
—
检测 SKILL.md 语言
en
星标 ★
41,524
分支 Fork
0
安装选项
提示
指令
使用 AI 助手安装
将下面的提示复制到你正在使用的 AI 助手中。
下载完整 Skill 目录(含全部配套文件)。 下载压缩包 ↓
SKILL.md 原文预览

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

| 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 imple

评论
Ggithub
github
github/awesome-copilot
查看 GitHub 仓库 查看作者的其他 Skill
来源信息
作者@github
所属大类测试与安全 Testing & Security / 测试
国内可用性通用
最近源活动—
风险提示访问网络
提示:风险标签为程序静态扫描结果,仅作提示,不代表安全认证。安装前请阅读 SKILL.md 及其引用的脚本、权限,自行判断是否可信。