mvvm-toolkit-di
Skill này làm gì
Skill này giúp kết nối các phần mã của bạn (gọi là ViewModel) với các phần khác cung cấp dịch vụ (như lưu tệp hoặc gửi tin nhắn) một cách có tổ chức. Nó dùng một hệ thống gọi là 'Dependency Injection' để các phần tự tìm thấy nhau.
Khi nào nên dùng
- ✓Khi bạn thiết lập một ứng dụng mới có giao diện đồ họa (WPF, MAUI, v.v.) và cần sắp xếp cách các phần của chương trình giao tiếp.
- ✓Khi bạn quyết định một dịch vụ hoặc ViewModel nên tồn tại trong bao lâu (mãi mãi, chỉ khi cần, v.v.).
- ✓Khi bạn cần đảm bảo giao tiếp tin nhắn giữa các phần ứng dụng được thiết lập đúng và có sẵn ở nơi cần.
Liên kết skill
https://github.com/github/awesome-copilot/blob/main/skills/mvvm-toolkit-di/SKILL.mdSao chép rồi dán vào AI của bạn (Claude, ChatGPT hoặc Cursor) và nhờ nó làm theo hướng dẫn.
Cách dùng
Cách dễ nhất: sao chép tin nhắn và dán vào AI của bạn. AI sẽ đọc skill và làm theo hướng dẫn.
Tin nhắn có sẵn để dán
Dành cho Claude Code, Codex hoặc Cursor: chạy lệnh trong thư mục dự án của bạn và skill sẽ được cài đặt.
Tải tệp SKILL.md về và thả vào thư mục skill của agent.
Ví dụ cách nhờ AI
“Làm thế nào để thiết lập ứng dụng của tôi để nó biết cách tạo và cung cấp các ViewModel và dịch vụ của tôi?”
5 skill mới mỗi tuần. Đọc chỉ 1 phút.
Cách hoạt động
Nó dùng một hệ thống gọi là 'Dependency Injection', hoạt động như một người sắp xếp. Bạn cho nó biết những dịch vụ nào tồn tại và cách tạo chúng, rồi nó tự động chuyển chúng đến nơi cần, thường qua constructor của các lớp.
Nội dung kỹ thuật (SKILL.md gốc)
Lấy nguyên văn từ GitHub, do tác giả viết bằng tiếng Anh.
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; }
…
Câu hỏi thường gặp
“Dependency Injection” là gì?
Đây là cách tổ chức mã trong đó, thay vì một lớp tự tạo các phụ thuộc (các lớp khác mà nó cần), các phụ thuộc đó được “tiêm” (cung cấp) từ bên ngoài. Điều này làm mã linh hoạt hơn và dễ kiểm thử hơn.
Singleton, Transient và Scoped khác nhau thế nào?
Singleton: chỉ có một thể hiện trong suốt vòng đời ứng dụng. Transient: một thể hiện mới được tạo mỗi lần được yêu cầu. Scoped: một thể hiện được tạo cho mỗi “phạm vi” cụ thể, như một cửa sổ hoặc một yêu cầu (ít gặp hơn trong ứng dụng desktop).
Vì sao không nên tự tạo ViewModel?
Tự tạo có thể khiến mã khó quản lý và kiểm thử hơn. Dùng “Dependency Injection” đảm bảo các phụ thuộc được giải quyết đúng, và bạn không phải lo cách tạo chúng mỗi lần.
Chi tiết
Mô tả gốc của tác giả
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
Độ phổ biến
- Sao GitHub
- 40k
- Vị trí xếp hạng
- #7302
- Giấy phép
- MIT
- Cập nhật
- 15/10/2026
Bình luận
- …
Thêm skill từ kho mã này
acquire-codebase-knowledge
40kGiúp agent của bạn hiểu và ghi tài liệu cho một dự án mã nguồn có sẵn. Hữu ích khi đón thành viên mới hoặc nắm tổng quan về kiến trúc.
acreadiness-assess
40kGiúp agent của bạn đánh giá mức độ sẵn sàng cho AI của dự án và tạo báo cáo. Hữu ích để biết dự án đã sẵn sàng dùng công cụ AI đến đâu.
acreadiness-generate-instructions
40kGiúp agent của bạn tạo hướng dẫn cho công cụ AI dựa trên kết quả đánh giá. Hữu ích để cải thiện cách AI làm việc với mã và khắc phục các khoảng trống.
acreadiness-policy
40kGiúp agent của bạn xác định hoặc áp dụng chính sách đánh giá dự án bằng AI. Hữu ích để chuẩn hóa cách đánh giá dự án và đảm bảo tuân thủ.
Skill tương tự
api-connector-builder
280kGiúp agent của bạn xây dựng kết nối API mới theo đúng mẫu đã có, dùng khi bạn cần thêm một tích hợp mà không tạo cách làm mới.
api-design
280kGiúp agent của bạn thiết kế REST API theo các thực hành tốt nhất, hữu ích để định nghĩa cách API giao tiếp, hiển thị lỗi và tổ chức dữ liệu.
backend-patterns
280kGiúp agent của bạn với các mẫu kiến trúc phía máy chủ và tối ưu cơ sở dữ liệu, hữu ích khi xây dựng hoặc rà soát code chạy trên máy chủ.