mvvm-toolkit-di
它能做什么
这个技能可以帮你把代码中的一部分(称为 ViewModel)和提供服务的其他部分(比如保存文件、发送消息)有条理地连接起来。它使用一种叫“依赖注入”(Dependency Injection)的机制,让正确的部分能够自动找到彼此。
适用场景
- ✓当你要新建一个带图形界面的应用(WPF、MAUI 等),需要理清程序各部分之间如何协作时。
- ✓当你需要决定某个服务或 ViewModel 应该存活多久(一直存在、按需创建等)时。
- ✓当你需要确保应用各部分之间的消息通信设置正确,并且在需要的地方可以使用时。
技能链接
https://github.com/github/awesome-copilot/blob/main/skills/mvvm-toolkit-di/SKILL.md复制后粘贴给你的 AI(Claude、ChatGPT 或 Cursor),让它按照说明操作。
使用方法
最简单的方法:复制下面的消息,粘贴给你的 AI。它会读取这个技能并按说明操作。
可直接粘贴的消息
适用于 Claude Code、Codex 或 Cursor:在项目文件夹中运行,即可安装该技能。
下载 SKILL.md,放进智能体的技能文件夹。
可以这样问 AI
“我该怎样设置应用,让它知道如何创建并提供我的 ViewModel 和服务?”
每周 5 个新技能,1 分钟读完。
工作原理
它使用一种叫“依赖注入”的机制,就像一个整理员。你告诉它有哪些服务、如何创建它们,它就会自动把这些服务交给需要它们的地方,通常是通过类的构造函数。
技术内容(原始 SKILL.md)
作者在 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. 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 intoObservableRecipientViewModels - 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.jsonbinding viaMicrosoft.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; }
…
常见问题
什么是“依赖注入”?
这是一种组织代码的方式。类不再自己创建它需要的依赖(也就是它需要的其他类),而是由外部把这些依赖“注入”(提供)进来。这样代码会更灵活,也更容易测试。
Singleton、Transient 和 Scoped 有什么区别?
Singleton:在整个应用生命周期中只存在一个实例。Transient:每次被请求时都会创建一个新实例。Scoped:在特定的“作用域”内创建一个实例,比如一个窗口或一次请求(在桌面应用中比较少见)。
为什么不应该手动创建 ViewModel?
手动创建可能让代码更难管理和测试。使用“依赖注入”可以确保依赖被正确解析,你也不必每次都操心如何创建它们。
详情
作者的原始描述
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.
repo: github/awesome-copilot
热度
- GitHub 星标
- 40k
- 排名
- #7302
- 许可证
- MIT
- 更新时间
- 2026/10/15
评论
- …
同一仓库的更多技能
acquire-codebase-knowledge
40k帮你的智能体理解并编写现有代码项目的文档。它有助于新成员快速上手,或者快速了解项目架构。
acreadiness-assess
40k让你的智能体评估一个项目对 AI 的准备程度,并生成报告。它有助于了解项目在使用 AI 工具方面的准备情况。
acreadiness-generate-instructions
40k帮你的智能体根据评估结果编写 AI 工具的指令文件。它有助于改善 AI 与代码的交互方式,并弥补已发现的不足。
acreadiness-policy
40k让你的智能体协助制定或应用 AI 项目评估的政策。它有助于规范项目的评估方式,并确保合规。