Skip to content

Custom Main

dragonfavors edited this page Nov 10, 2026 · 5 revisions

커스텀 Main

문서 홈

업데이트 확인·단일 실행 검사처럼 WPF 실행 전 작업이 필요할 때 사용합니다. 앱이 Main과 호스트를 만들고 Gyedo가 비동기 시작·정리를 연결합니다.

실행 가능한 전체 예제는 CustomStartup에 있습니다.

진입점 설정

일반 WPF 프로젝트에 Gyedo.Wpf를 참조한 뒤 프로젝트 파일에 추가합니다.

<PropertyGroup>
    <StartupObject>DemoApp.App</StartupObject>
</PropertyGroup>
<ItemGroup>
    <ApplicationDefinition Remove="App.xaml" />
    <Page Include="App.xaml" />
</ItemGroup>

DemoApp.App은 실제 App 클래스의 전체 이름으로 바꿉니다. App.xaml에는 일반 리소스만 두며 StartupUri와 ApplicationLoader를 넣지 않습니다.

App이 호스트를 구성하기

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Gyedo;
using System;
using System.Diagnostics;
using System.Windows;

namespace DemoApp;

public partial class App : Application
{
    public IHost Host { get; private set; } = null!;

    [STAThread]
    public static int Main(string[] args)
    {
        // 앱의 사전 작업. 실행하지 않을 조건이면 여기서 반환합니다.
        var app = new App();
        app.InitializeComponent();
        app.Host = Microsoft.Extensions.Hosting.Host.CreateDefaultBuilder(args)
            .UseContentRoot(AppContext.BaseDirectory)
            .ConfigureGyedo(app, views => views.ViewModelNameSuffix = "VM")
            .ConfigureServices((_, services) => services.AddSingleton<MainVM>())
            .Build();
        return app.Run();
    }

    protected override async void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);
        try
        {
            if (!await this.StartGyedoAsync(this.Host))
                return;

            // 폰트·테마 등 화면 표시 전의 UI 초기화
            await this.Host.Services.GetRequiredService<IWindowManager>()
                .ShowWindowAsync(this.Host.Services.GetRequiredService<MainVM>());
        }
        catch (Exception exception)
        {
            Trace.TraceError("앱 시작 실패: {0}", exception);
            await this.ShutdownGyedoAsync(1);
        }
    }
}

위 예시는 MainVM : Screen과 WPF MainView를 함께 작성한 경우입니다. 이름 접미사 설정이 MainVM → MainView를 연결합니다. 기본 규칙인 MainViewModel → MainView를 쓰면 옵션 설정을 생략합니다.

두 종류의 호스트 빌더

Host.CreateApplicationBuilder에도 같은 등록 API를 사용할 수 있습니다. 다음은 Main 안에서 호스트를 만드는 부분만 바꾼 예입니다.

var builder = Microsoft.Extensions.Hosting.Host.CreateApplicationBuilder(args);
builder.ConfigureGyedo(app);
builder.Services.AddSingleton<MainViewModel>();
app.Host = builder.Build();

이 경우 첫 화면 조회도 MainViewModel로 맞춥니다. 설정·로깅·서비스 구성은 앱이 원하는 순서로 작성합니다.

지켜야 할 순서

  • ConfigureGyedo은 호스트당 한 번 호출합니다. 첫 VM은 자동 등록하지 않습니다.
  • StartGyedoAsync는 같은 Application으로 구성한 호스트를 WPF UI 스레드의 OnStartup에서 연결합니다.
  • Dispatcher, ViewManager 리소스, 기본 Conductor 스타일이 연결됩니다. 기존 앱 리소스는 유지합니다.
  • 시작 중 호스트가 종료를 요청하면 false를 반환합니다. 이때 화면을 만들지 않습니다.
  • 연결 후에는 Gyedo가 호스트 시작·정상 종료·폐기를 담당합니다. Host.StartAsync를 미리 호출하거나 중복 폐기하지 않습니다.
  • 앱 종료는 ShutdownGyedoAsync()로 요청합니다. 창의 종료 조건과 정리를 확인한 뒤 호스트를 폐기합니다.

호스트를 미리 빌드해도 WPF 수명 연결은 StartGyedoAsync 시점에 수행합니다. VM과 업무 서비스는 명시적으로 등록하세요.

다음: 호스트와 DI

Clone this wiki locally