gpt4 book ai didi

c# - 发布为 windows 服务后,在 .net core 3.0 worker 服务上获取 appsettings.json 值

转载 作者:行者123 更新时间:2023-11-30 17:25:32 26 4
gpt4 key购买 nike

在回答之后: .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);
}
}
}

应用设置.json:

{
"ConnectionStrings": {
"WFoneConnection": ""
},
"ServiceConfigurations": {
"UrlSignalrNotification": "urlValue",
"WatchIp": "ipValue",
"WatchPort": "portValue"
},
"ServiceSettings": {
"PathLog": "C:\\Log\\"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
}
}

最佳答案

有几种方法可以解决这个问题。

  1. 你可以使用 dotnet new worker 模板

dotnet new worker

  1. 在 .csproj 中手动将项目类型更改为 Microsoft.NET.Sdk.Worker

<Project Sdk="Microsoft.NET.Sdk.Worker">

  1. 在您的 .csproj 中添加您的 appsettings.json 文件并将其复制到输出目录
  <ItemGroup>
<None Update="appsettings.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>

如果您有一个现有项目,我建议您将您的 csproj 转换为我们的 Worker Sdk,或者如果创建一个新项目很简单,请使用 #1。 #3 只是将 appsettings.json 文件复制到您的输出中是一个可怕的技巧,我不推荐这样做。

关于c# - 发布为 windows 服务后,在 .net core 3.0 worker 服务上获取 appsettings.json 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58308476/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com