遵循答案: .NET Core 3 Worker Service Settings Dependency Injection
我可以通过Worker.cs类在Debug或Release中获取设置。 但是当作为Windows服务部署时,此值将返回null
Worker.cs
public class Worker : BackgroundService
{
private readonly ILogger<Worker> _logger;
private readonly ServiceSettings _serviceSettings;
private readonly ServiceConfigurations _serviceConfigurations;
public Worker(ILogger<Worker> logger, IOptions<ServiceConfigurations> serviceConfigurations, IOptions<ServiceSettings> serviceSettings)
{
_logger = logger;
_serviceConfigurations = serviceConfigurations.Value;
_logger.LogInformation($"Worker running at: {DateTime.Now}");
_serviceSettings = serviceSettings.Value;
string retornoPathLog = null;
string PathLog = _serviceSettings.PathLog;
if (!Directory.Exists(PathLog))
{
retornoPathLog = "Diretório de LOG " + PathLog;
Directory.CreateDirectory(PathLog);
}
//Configure Serilo for Logging
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Information()
.Enrich.FromLogContext()
.WriteTo.File(PathLog + "log.txt", rollingInterval: RollingInterval.Day)
.CreateLogger();
if (string.IsNullOrEmpty(retornoPathLog) == false)
{
Log.Information("[WFoneService - Watch Event] " + retornoPathLog);
}
}
}
appsettings.json:
{
"ConnectionStrings": {
"WFoneConnection": ""
},
"ServiceConfigurations": {
"UrlSignalrNotification": "urlValue",
"WatchIp": "ipValue",
"WatchPort": "portValue"
},
"ServiceSettings": {
"PathLog": "C:\\Log\\"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
}
}
答案 0 :(得分:1)
有几种方法可以解决此问题。
dotnet new worker
<Project Sdk="Microsoft.NET.Sdk.Worker">
<ItemGroup>
<None Update="appsettings.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
如果您有一个现有项目,我建议#2将您的csproj转换为Worker Sdk,或者,如果只需创建一个新项目,则使用#1。 #3是一个可怕的骇客,只是将appsettings.json文件复制到输出中,我不建议这样做。
答案 1 :(得分:0)
由于缺乏对.NET Core 3.0的经验,我停止了向项目中添加程序包,并按照Microsoft网站上的文档找到了解决方案。 我解决了如下问题
在Program.cs文件中,添加了.UseWindowsService()并添加了Microsoft.Extensions.Hosting.WindowsServices程序包,如下面的链接中所述。