Reputation: 61
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"
}
}
}
Upvotes: 5
Views: 7198
Reputation: 61
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.
Upvotes: 1
Reputation: 2333
There are a few ways to handle this.
dotnet new worker
<Project Sdk="Microsoft.NET.Sdk.Worker">
<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.
Upvotes: 2