c# - 如何为BackgroundService传递参数?
问题描述
我阅读了有关 ASP.net core 2.2 的信息,并找到了有关通用主机的参考资料。
我尝试在示例下使用 backgroundService 创建控制台应用程序:https ://github.com/aspnet/AspNetCore.Docs/tree/master/aspnetcore/fundamentals/host/generic-host/samples/
var param = Console.ReadLine();
var host = new HostBuilder().ConfigureServices((hostContext, services) =>
{
services.AddHostedService<MyCustomSerivce>();
}
问题是如何从命令行传递参数(在我的例子中是'param'),这将在特定的后台服务中指定内部逻辑。
解决方案
为了解析服务,您需要将参数注册到服务集合中。
参数存储服务
public class CommandLineArgs { public string Args { get; set; } }
注册参数
public class Program { public static async Task Main(string[] args) { var param = Console.ReadLine(); var host = new HostBuilder() .ConfigureHostConfiguration(configHost => { configHost.SetBasePath(Directory.GetCurrentDirectory()); configHost.AddJsonFile("hostsettings.json", optional: true); configHost.AddEnvironmentVariables(prefix: "PREFIX_"); configHost.AddCommandLine(args); }) .ConfigureAppConfiguration((hostContext, configApp) => { configApp.AddJsonFile("appsettings.json", optional: true); configApp.AddJsonFile( $"appsettings.{hostContext.HostingEnvironment.EnvironmentName}.json", optional: true); configApp.AddEnvironmentVariables(prefix: "PREFIX_"); configApp.AddCommandLine(args); }) .ConfigureServices((hostContext, services) => { services.AddSingleton(new CommandLineArgs { Args = param }); services.AddHostedService<LifetimeEventsHostedService>(); services.AddHostedService<TimedHostedService>(); }) .ConfigureLogging((hostContext, configLogging) => { configLogging.AddConsole(); configLogging.AddDebug(); }) .UseConsoleLifetime() .Build(); await host.RunAsync(); } }
解决服务
internal class TimedHostedService : IHostedService, IDisposable { private readonly ILogger _logger; private Timer _timer; private readonly IConfiguration _configuration; private readonly CommandLineArgs _commandLineArgs; public TimedHostedService(ILogger<TimedHostedService> logger , IConfiguration configuration , CommandLineArgs commandLineArgs) { _logger = logger; _configuration = configuration; _commandLineArgs = commandLineArgs; } }
推荐阅读
- python - 将 pygame 2d 水波纹转换为 pyOpenGL
- python-3.x - 如何显示广告横幅取决于日期时间?
- javascript - 如何将包含值、值的对象的数组转换为只有键、值的单个对象?
- python - Django 本地主机上的错误请求(400)
- javascript - TensorFlow mobilenet 离线使用模型
- python-3.x - 进入全屏模式会隐藏任务栏中的图标,并且应用程序从后台运行
- salesforce - 我是否可以将 Salesforce Community Cloud 作为身份提供者将 SAML SSO 用于我的应用程序?
- node.js - 无法 Dockerize 我的简单打字稿网站
- c - 这是一个便携式的 strdup
- javascript - 如何使用 Google 表格中的数据将数组插入 Google Doc?