Я начал с нескольких настроек.< /p>
Мой файл appsettings.Development.json имеет следующее содержимое:
Код: Выделить всё
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"ConnectionStrings": {
"PlannedOutageConn": "Data Source=localhost;Initial Catalog=planned_outage;Persist Security Info=True;User ID=User;Password=password;Trust Server Certificate=True"
},
"Settings": {
"corsOrigin": "http://Server1",
"plannedOutageWebService": "https://localhost:7400/api/triview",
"verboseLogging": true
}
Код: Выделить всё
namespace PlannedOutageWindowsSvc.Models
{
///
/// A class representing the various app configurations found in appsettings.{environment}.json
///
public class SettingsConfig
{
///
/// The origin host e.g. http://localhost or https://Server1
///
public string corsOrigin { get; set; } = "";
///
/// Api endpoint for Planned Outage Web Service
///
public string plannedOutageWebService { get; set; } = "";
///
/// Dictates if verbose logging is on or off (boolean)
///
public bool verboseLogging { get; set; }
}
}
Код: Выделить всё
using App.WindowsService;
using Microsoft.EntityFrameworkCore;
using PlannedOutageWindowsSvc.Models;
using NLog;
using NLog.Web;
using System.Reflection;
using Microsoft.Extensions.DependencyInjection;
var builder = Host.CreateApplicationBuilder(args);
builder.Services.AddWindowsService(options =>
{
options.ServiceName = "PlannedOutageWinSvc";
});
var env = Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT");
IConfiguration config = new ConfigurationBuilder()
.AddJsonFile($"appsettings.json", false, true)
.AddJsonFile($"appsettings.{env}.json", true, true)
.AddEnvironmentVariables()
.Build();
// Early init of NLog to allow startup and exception logging, before host is built
var mlogger = NLog.LogManager.Setup().LoadConfigurationFromAppSettings().GetCurrentClassLogger();
mlogger.Warn("PlannedOutageWindowsService is being initiated");
try
{
//DB connection/context
builder.Services.AddDbContext
(
options => options.UseSqlServer(builder.Configuration.GetConnectionString("PlannedOutageConn")));
builder.Services.Configure(config.GetSection("Settings"));
builder.Services.AddHostedService();
builder.Services.AddSingleton();
IHost host = builder.Build();
host.Run();
}
catch (Exception ex)
{
// NLog: catch setup errors
mlogger.Error(ex, "PlannedOutageWindowsService stopped because of exception");
throw;
}
finally
{
// Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux)
NLog.LogManager.Shutdown();
}
Код: Выделить всё
using PlannedOutageWindowsSvc.Models;
using System.Text.Json;
namespace App.WindowsService
{
public class PlannedOutageService()
{
private SettingsConfig svcSettings;
public PlannedOutageService(SettingsConfig? appSettings) //ERROR CS8863
{
svcSettings = appSettings;
}
public static async Task ProcessTriViewMessages()
{
//THIS IS WHERE I WANT TO ACCESS THE SETTINGS VALUES
string triviewUrl = svcSetting.plannedOutagesWebService; //ERROR CS0120
// ..... other code removed
}
}
}
CS8862 Конструктор, объявленный в типе с параметром список должен иметь инициализатор конструктора this.
CS0120 Требуется ссылка на объект для нестатического поля, метода, или свойство PlannedOutageService.svcSettings
Как мне получить доступ к своим настройкам в одном элементе? Большое спасибо
Подробнее здесь: https://stackoverflow.com/questions/787 ... net-core-8