发布为Windows Service后在.net Core 3.0 Worker服务上获取appsettings.json值

时间:2019-10-09 16:26:39

标签: c# asp.net-core

遵循答案: .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"
    }
  }
}

2 个答案:

答案 0 :(得分:1)

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

  1. 您可以使用dotnet新工作程序模板

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>

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

答案 1 :(得分:0)

由于缺乏对.NET Core 3.0的经验,我停止了向项目中添加程序包,并按照Microsoft网站上的文档找到了解决方案。 我解决了如下问题

在Program.cs文件中,添加了.UseWindowsService()并添加了Microsoft.Extensions.Hosting.WindowsServices程序包,如下面的链接中所述。

https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/windows-service?view=aspnetcore-3.0&tabs=visual-studio