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에 붙여넣으세요. 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 프로젝트 평가를 위한 정책을 정의하거나 적용하도록 돕습니다. 프로젝트 평가 방식을 표준화하고 규정 준수를 보장할 때 유용합니다.
비슷한 스킬
api-connector-builder
280k에이전트가 기존 패턴을 따라 새로운 API 연결을 만들도록 합니다. 새로운 방식을 도입하지 않고 연동을 하나 더 추가할 때 씁니다.
api-design
280k에이전트가 모범 사례에 따라 REST API를 설계하도록 돕습니다. API가 통신하는 방식, 오류를 보여 주는 방식, 데이터를 정리하는 방식을 정하는 데 유용합니다.
backend-patterns
280k에이전트가 서버 쪽 아키텍처 패턴과 데이터베이스 최적화를 다루도록 돕습니다. 서버에서 실행되는 코드를 만들거나 검토할 때 유용합니다.