c# - 为什么我的 BackgroundService Args 始终为空?
问题描述
我在 .Net Core 3.1 中使用 BackgroundService。
有两段代码,第一段是 BackgroundService 本身,我以它的已发布格式使用它。使用以下指南中的相同方法:https ://youtu.be/PzrTiz_NRKA?t=2050
第二个项目是一个服务控制器,我试图用它来启动服务并将参数传递给它。
主要的后台服务应用程序:
public class Program
{
public static void Main(string[] args)
{
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
.Enrich.FromLogContext()
.WriteTo.File(@"C:\temp\workerservice\logfile.txt")
.CreateLogger();
Log.Information($"Test Args Given {args}");
var param = Console.ReadLine();
Log.Information($"Params {string.Join("", args)}");
try
{
Log.Information("Starting The Service");
Log.Information($"Args Given {string.Join("", args)}");
CreateHostBuilder(args).Build().Run();
return;
}
catch (Exception ex)
{
Log.Fatal(ex, "Problem Starting the Service");
return;
}
finally {
Log.CloseAndFlush();
}
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseWindowsService()
.ConfigureServices((hostContext, services) =>
{
IConfiguration configuration = hostContext.Configuration;
DriverConfig options = configuration.GetSection("DriverConfig").Get<DriverConfig>();
Log.Information($"Running with options {options.DriverName} at {options.IpAddress}");
services.AddSingleton(options);
services.AddSingleton<CustomDriver, ExampleDriver>();
services.AddHostedService<DriverSetup>();
}).UseSerilog();
}
第二个代码片段是在控制台应用程序中运行的服务控制器(作为管理员):
该服务以名称“MQTTArgless”发布,它被拾取并正确启动服务。参数似乎也被解析了。所以问题似乎不在这部分代码中。
static void Main(string[] args)
{
ServiceController[] objService;
objService = ServiceController.GetServices();
string[] Driver1Config = new string[] { "DriverTemplate", "http://localhost:5001"};
foreach (ServiceController SController in objService)
{
if (SController.ServiceName == "MQTTArgless")
{
ServiceController sc = new ServiceController("MQTTArgless", "MSI");
Console.WriteLine("Status = " + sc.Status);
Console.WriteLine("Can Pause and Continue = " + sc.CanPauseAndContinue);
Console.WriteLine("Can ShutDown = " + sc.CanShutdown);
Console.WriteLine("Can Stop = " + sc.CanStop);
string[] argArray = new string[] { "MQTTArgless", "http://MSI:5001" };
sc.Start(argArray);
sc.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(30));
}
}
}
问题是从 Worker 服务中我看不到任何参数,因为 args 以 null 形式出现。任何建议/帮助将不胜感激。
解决方案
推荐阅读
- asp.net-mvc - asp.net MVC 登录用户仍然路由到登录页面
- superset - 如何在超集中更改自定义仪表板的标签颜色
- kubernetes - Kubernetes 不断创建对象
- node.js - 错误:当我执行“sequelize db:migrate”时,“请手动安装 sqlite3 包”
- search - 颤振将变量传递给 SearchDelegate 类给出错误
- android - 触摸列表中的项目后防止多次触摸
- java - 在 Java 8 中是否有更简洁的方法来执行此操作 - 地图操作
- flutter - 在我的项目中,导入'package:flare_flutter/flare_actor.dart';不导入显示错误以及在 FlareActor 中?
- javascript - 搜索数据表后如何保留对数据表所做的修改
- ruby-on-rails - 我可以将不属于模型的测试数据放在哪里?