Chuyển đến nội dung
Skillpedia
API và máy chủ (backend)40k · #7302

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.md

Sao 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

Hãy dùng skill này để giúp tôi: https://github.com/github/awesome-copilot/blob/main/skills/mvvm-toolkit-di/SKILL.md Đọc tệp SKILL.md tại liên kết đó và làm theo hướng dẫn cho việc của tôi.
Bạn muốn AI tự tìm những skill như thế này?Cài MCP Skillpedia miễn phí: chỉ một dòng, và AI sẽ tìm trong 15.000+ skill trước mỗi việc.Cài đặt trong 1 phút →

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. 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; }


…
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

Skill này có hữu ích không?

0

Đăng nhập để bình chọn.

Bình luận

  • …

Thêm skill từ kho mã này

Skill tương tự