本文へスキップ
Skillpedia
APIとサーバー(バックエンド)40k · #7302

mvvm-toolkit-di

できること

このskillは、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に貼り付けるだけ。AIがスキルを読んで指示に従います。

貼り付け用メッセージ

このスキルを使って手伝ってください:https://github.com/github/awesome-copilot/blob/main/skills/mvvm-toolkit-di/SKILL.md このリンクのSKILL.mdファイルを読んで、私の作業でその指示に従ってください。
こういうスキルを、AIが自分で見つけてくれたら?無料のSkillpedia MCPをインストール。1行で、作業の前に15,000+のスキルから探してくれます。1分でインストール →

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


…
よくある質問

「依存性の注入」(Dependency Injection)とは何ですか?

クラスが自分で必要な部品(依存先の別のクラス)を作るのではなく、外側からその部品を「注入」(提供)してもらう書き方のことです。これによりコードの柔軟性が高まり、テストもしやすくなります。

Singleton、Transient、Scopedの違いは何ですか?

Singletonはアプリの実行中、インスタンスが1つだけ存在します。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

このスキルは役に立ちますか?

0

ログイン して投票しましょう。

コメント

  • …

このリポジトリの他のスキル

似ているスキル