備忘録

備忘録

コンソールアプリケーションでGeneric Hostを利用する方法

Ⅰ. はじめに

タイトルの通り「コンソールアプリケーションでGeneric Hostを利用する方法」です。

Ⅱ. やり方

1. 必要なパッケージをインストールする
Install-Package Microsoft.Extensions.Hosting
2. サンプルプログラムを書く
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

var builder = new HostBuilder()
   .ConfigureServices((hostContext, services) =>
   {
     services.Configure<HostOptions>(options =>
     {
       // options.ServicesStartConcurrently = true; // .NET 8 以降
       // options.ServicesStopConcurrently = true; // .NET 8 以降
     });
     services.AddHostedService<MyService>();
   });
await builder.RunConsoleAsync();

public class MyService : IHostedService
{
  private readonly IHostApplicationLifetime AppLifetime;

  public MyService(IHostApplicationLifetime appLifetime)
  {
    AppLifetime = appLifetime;
  }

  public Task StartAsync(CancellationToken cancellationToken)
  {
    Console.WriteLine("StartAsync");

    AppLifetime.ApplicationStarted.Register(OnStarted);
    AppLifetime.ApplicationStopping.Register(OnStopping);
    AppLifetime.ApplicationStopped.Register(OnStopped);

    return Task.CompletedTask;
  }

  public void OnStarted()
  {
    Console.WriteLine("OnStarted");
  }

  public void OnStopping()
  {
    Console.WriteLine("OnStopping");
  }

  public Task StopAsync(CancellationToken cancellationToken)
  {
    Console.WriteLine("StopAsync");
    return Task.CompletedTask;
  }

  public void OnStopped()
  {
    Console.WriteLine("OnStopped");
  }
}

実行結果

StartAsync
OnStarted

※Ctrl + Cを入力すると以下がコンソールに出力されます。

OnStopping
StopAsync
OnStopped