简体   繁体   中英

Get appsettings.json values on .net core 3.0 worker service after publish as windows service

Following the answer: .NET Core 3 Worker Service Settings Dependency Injection

I can get the settings in Debug or in Release, at class Worker.cs But when deployed as Windows Service, this values return as 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"
    }
  }
}

There are a few ways to handle this.

  1. you can use the dotnet new worker template

dotnet new worker

  1. Manually change your project type to Microsoft.NET.Sdk.Worker in your.csproj

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

  1. In your.csproj add your appsettings.json file and have it copied to the output directory
  <ItemGroup>
    <None Update="appsettings.json">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </None>
  </ItemGroup>

If you have an existing project I'd recommend #2 convert your csproj to us the Worker Sdk, alternatively if its simple to just create a new project use #1. #3 is a terrible hack just to copy out the appsettings.json file to your output, I don't recommend this.

Due to lack of experience with .NET core 3.0, I stopped adding a package to the project, and following a documentation from the Microsoft website I found the solution. I solved the problem as follows

In the Program.cs file, I added.UseWindowsService () and added the Microsoft.Extensions.Hosting.WindowsServices package as documented in the link below.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM