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がスキルを読んで指示に従います。
貼り付け用メッセージ
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; }
…
よくある質問
「依存性の注入」(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
コメント
- …
このリポジトリの他のスキル
acquire-codebase-knowledge
40kエージェントが、既存のコードプロジェクトを理解してドキュメント化できるよう支援します。新しく参加するメンバーのオンボーディングや、アーキテクチャの全体像の把握に役立ちます。
acreadiness-assess
40kエージェントが、プロジェクトのAI対応状況を評価してレポートを生成できるよう支援します。プロジェクトがAIツールをどの程度活用できる状態にあるかを把握するのに役立ちます。
acreadiness-generate-instructions
40kエージェントが、評価結果をもとにAIツール向けの指示文を作成できるよう支援します。AIがコードとどのようにやり取りするかを改善し、特定された不足点を解消するのに役立ちます。
acreadiness-policy
40kエージェントが、AIプロジェクトの評価ポリシーの策定や適用を支援できるようにします。プロジェクトの評価方法を標準化し、コンプライアンスを確保するのに役立ちます。
似ているスキル
api-connector-builder
280kエージェントが既存のパターンに従って、新しいAPI連携を構築します。新しい方式を作らずに、もう一つ連携を追加したいときに使います。
api-design
280kエージェントがベストプラクティスに沿ってREST APIを設計できるようにします。APIの通信方法、エラーの表示方法、データの整理方法を決めるのに役立ちます。
backend-patterns
280kエージェントのサーバーサイドのアーキテクチャパターンとデータベースの最適化を支援します。サーバー上で動くコードを作成またはレビューするときに役立ちます。