.NET コンソールアプリで、DI(Dependency Injection) をするには、Generic Host を使います。
public class Program
{
	public static void Main(string[] args)
	{
		IHost host = Host.CreateDefaultBuilder(args)
			.ConfigureServices(services =>
			{
				// DI
				services.AddTransient<IDemo001, Demo001>();
				services.AddScoped<IDemo002, Demo002>();
				services.AddSingleton<IDemo003, Demo003>();
				services.AddHostedService<Worker>();
			})				
			.Build();			
		host.Run();
	}
}
IConfiguration も DI で取得できるようになるので、appsettings.json からの構成情報の読み取りも簡単です。
public class Demo001 : IDemo001
{
	private readonly string _connectionString;
	public Demo001(IConfiguration configuration)
	{
		_connectionString = configuration["testCofiguration:connectionString"] 
			?? throw new InvalidOperationException();
	}
}
Generic Host のプロジェクト テンプレートが用意されているので、これを使うと便利です。 dotnet コマンドでは、dotnet new worker で作成できます。
> dotnet new update
> dotnet new list
> dotnet new worker -n <プロジェクト名>
- https://learn.microsoft.com/ja-jp/dotnet/core/tools/dotnet-new-update
 - https://learn.microsoft.com/ja-jp/dotnet/core/tools/dotnet-new-list
 - https://learn.microsoft.com/ja-jp/dotnet/core/tools/dotnet-new
 
Visual Studio 2022 の場合は、"ワーカー サービス" を選択してください。

以上、参考までに。
コメント (0)
コメントの投稿