【发布时间】:2021-07-03 20:53:55
【问题描述】:
我正在构建一个简单的 .NET Core 控制台应用程序,它将从命令行读取基本选项,然后在没有用户交互的情况下执行和终止。我想利用 DI,从而引导我使用 .NET Core 通用主机。
我发现的所有构建控制台应用程序的示例都创建了一个实现 IHostedService 或扩展 BackgroundService 的类。然后该类通过 AddHostedService 添加到服务容器中,并通过 StartAsync 或 ExecuteAsync 启动应用程序的工作。但是,似乎在所有这些示例中,它们都在实现后台服务或其他一些在循环中运行或等待请求直到它被操作系统关闭或接收到一些终止请求的应用程序。如果我只想要一个启动、执行它的操作然后退出的应用程序怎么办?例如:
程序.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<MyServiceOptions>(hostContext.Configuration);
services.AddHostedService<MyService>();
services.AddSingleton(Console.Out);
});
}
}
MyServiceOptions.cs:
namespace MyApp
{
public class MyServiceOptions
{
public int OpCode { get; set; }
public int Operand { get; set; }
}
}
MyService.cs:
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<MyServiceOptions> 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
但是,在那之后,应用程序会一直等待,直到我按下 Ctrl+C。我知道我可以在工作完成后强制关闭应用程序,但是在这一点上,我觉得我没有正确使用 IHostedService。似乎它是为重复的后台进程而设计的,而不是像这样的简单控制台应用程序。但是,在 DoOperation 可能需要 20-30 分钟的实际应用程序中,我想利用 StopAsync 方法在终止之前进行清理。我也知道我可以自己创建服务容器等等,但是 .NET Core 通用主机已经做了很多我想做的事情。它似乎是编写控制台应用程序的正确方法,但如果不添加启动实际工作的托管服务,我如何让应用程序真正做任何事情?
【问题讨论】:
-
如果您只想要一个 DI 容器,为什么不在标准控制台应用程序中创建一个
ServiceCollection? -
这不是我想要的。我想使用诸如日志记录、配置和主机生命周期管理之类的东西。我知道我可以自己配置和使用这些服务,但似乎 .NET Core 通用主机是专门为它设计的。
标签: c# .net-core console-application