发布为 Windows 服务后获取 .net core 3.0 辅助服务上的 appsettings.json 值

Gus*_*ipi 5 c# asp.net-core

按照答案:\n .NET Core 3 Worker 服务设置依赖注入

\n\n

我可以在 Worker.cs 类的“调试”或“发布”中获取设置\n但是当部署为 Windows 服务时,此值返回为 null

\n\n

工人.cs

\n\n
public class Worker : BackgroundService\n{\n    private readonly ILogger<Worker> _logger;\n    private readonly ServiceSettings _serviceSettings;\n    private readonly ServiceConfigurations _serviceConfigurations;\n\n    public Worker(ILogger<Worker> logger, IOptions<ServiceConfigurations> serviceConfigurations, IOptions<ServiceSettings> serviceSettings) \n    {\n        _logger = logger;\n        _serviceConfigurations = serviceConfigurations.Value;\n\n        _logger.LogInformation($"Worker running at: {DateTime.Now}");\n        _serviceSettings = serviceSettings.Value;\n\n        string retornoPathLog = null;\n        string PathLog = _serviceSettings.PathLog;\n\n        if (!Directory.Exists(PathLog))\n        {\n            retornoPathLog = "Diret\xc3\xb3rio de LOG " + PathLog;\n            Directory.CreateDirectory(PathLog);\n        }\n\n        //Configure Serilo for Logging\n        Log.Logger = new LoggerConfiguration()\n            .MinimumLevel.Information()\n            .Enrich.FromLogContext()\n            .WriteTo.File(PathLog + "log.txt", rollingInterval: RollingInterval.Day)\n            .CreateLogger();\n\n        if (string.IsNullOrEmpty(retornoPathLog) == false)\n        {\n            Log.Information("[WFoneService - Watch Event] " + retornoPathLog);\n        }\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

应用程序设置.json:

\n\n
{\n  "ConnectionStrings": {\n    "WFoneConnection": ""\n  },\n  "ServiceConfigurations": {\n    "UrlSignalrNotification": "urlValue",\n    "WatchIp": "ipValue",\n    "WatchPort": "portValue"\n  },\n  "ServiceSettings": {\n    "PathLog": "C:\\\\Log\\\\"\n  },\n  "Logging": {\n    "LogLevel": {\n      "Default": "Information",\n      "Microsoft": "Warning",\n      "Microsoft.Hosting.Lifetime": "Information"\n    }\n  }\n}\n
Run Code Online (Sandbox Code Playgroud)\n

awr*_*t18 2

有几种方法可以处理这个问题。

  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>
Run Code Online (Sandbox Code Playgroud)

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