본문으로 건너뛰기
Skillpedia
API 및 서버 (백엔드)40k · #7302

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가 스킬을 읽고 지침을 따릅니다.

바로 붙여넣을 수 있는 메시지

Use this skill to help me: https://github.com/github/awesome-copilot/blob/main/skills/mvvm-toolkit-di/SKILL.md Read the SKILL.md file at that link and follow its instructions for my task.
AI가 이런 스킬을 알아서 찾아 쓰길 원하시나요?무료 Skillpedia MCP를 설치하세요. 한 줄이면 작업마다 스킬 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; }


…
자주 묻는 질문

'의존성 주입'은 무엇인가요?

클래스가 필요한 다른 클래스를 스스로 만드는 대신, 외부에서 그 의존성을 주입(제공)받도록 코드를 정리하는 방식입니다. 이렇게 하면 코드가 더 유연해지고 테스트하기 쉬워집니다.

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.

이 스킬이 유용한가요?

0

로그인 투표하려면 로그인하세요.

댓글

  • …

이 저장소의 다른 스킬

비슷한 스킬