Все найденные мной примеры создания консольного приложения создают класс который либо реализует IHostedService, либо расширяет BackgroundService. Затем этот класс добавляется в контейнер службы через AddHostedService и запускает работу приложения через StartAsync или ExecuteAsync. Однако кажется, что во всех этих примерах они реализуют фоновую службу или какое-то другое приложение, которое работает в цикле или ждет запросов, пока оно не будет отключено ОС или не получит какой-либо запрос на завершение. Что, если мне просто нужно, чтобы приложение запускалось, выполняло свою работу, а затем закрывалось? Например:
Program.cs:
Код: Выделить всё
namespace MyApp
{
using System;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
public static class Program
{
public static async Task Main(string[] args)
{
await CreateHostBuilder(args).RunConsoleAsync();
}
private static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseConsoleLifetime()
.ConfigureLogging(builder => builder.SetMinimumLevel(LogLevel.Warning))
.ConfigureServices((hostContext, services) =>
{
services.Configure(hostContext.Configuration);
services.AddHostedService();
services.AddSingleton(Console.Out);
});
}
}
Код: Выделить всё
namespace MyApp
{
public class MyServiceOptions
{
public int OpCode { get; set; }
public int Operand { get; set; }
}
}
Код: Выделить всё
namespace MyApp
{
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;
public class MyService : IHostedService
{
private readonly MyServiceOptions _options;
private readonly TextWriter _outputWriter;
public MyService(TextWriter outputWriter, IOptions options)
{
_options = options.Value;
_outputWriter = outputWriter;
}
public async Task StartAsync(CancellationToken cancellationToken)
{
_outputWriter.WriteLine("Starting work");
DoOperation(_options.OpCode, _options.Operand);
_outputWriter.WriteLine("Work complete");
}
public async Task StopAsync(CancellationToken cancellationToken)
{
_outputWriter.WriteLine("StopAsync");
}
protected void DoOperation(int opCode, int operand)
{
_outputWriter.WriteLine("Doing {0} to {1}...", opCode, operand);
// Do work that might take awhile
}
}
}
Код: Выделить всё
Starting work
Doing 1 to 2...
Work complete
Подробнее здесь: https://stackoverflow.com/questions/669 ... d-services