我一直在开发一个提供数据给VBA应用程序的应用程序,现在正在尝试获取配置文件(appsettings.json和appsettings.Development.Json)。目前它是一个.net6.0控制台应用程序,稍后我会将其制作成一个IconTrayApp。
遇到了一个问题,主要的Program.cs方法获取appsettings.json文件,而工作者则获取appssettings.Developement.json文件。我明白为什么Main()获取无环境JSON文件,因为我特意加载它。但我希望应用程序在IDE内外都使用相同的文件。
这是program.cs文件:
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using PostDataService.InterfaceModels;
using Serilog;
using Serilog.Events;
using System;
namespace PostDataService
{
public class Program
{
public static void Main(string[] args)
{
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
IConfiguration config = builder.Build();
string _logFQN = config["PostConfig:Basefolder"] + config["PostConfig:LogsFolder"] + config["PostConfig:LogFname"];
string _LogTemplate = config["PostConfig:LogTemplate"];
var loggerConfig = new LoggerConfiguration()
.MinimumLevel.Override("Microsoft", LogEventLevel.Verbose)
.Enrich.FromLogContext()
.Enrich.WithThreadId()
.Enrich.WithEnvironmentUserName()
.WriteTo.File(_logFQN,
fileSizeLimitBytes: 524288000,
rollOnFileSizeLimit: true,
rollingInterval: RollingInterval.Day,
outputTemplate: _LogTemplate);
Log.Logger = loggerConfig.CreateLogger();
try
{
Log.Write(LogEventLevel.Information, "Start USPS Data Server");
CreateHostBuilder(args).Build().Run();
}
catch (Exception ex)
{
Log.Fatal(ex, "Host terminated unexpectedly");
}
finally
{
Log.Information("USPS Server stopped");
Log.CloseAndFlush();
}
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseSerilog()
.ConfigureServices((hostContext, services) =>
{
IConfiguration configuration = hostContext.Configuration;
WorkerOptions options = configuration.GetSection("PostConfig").Get<WorkerOptions>();
services.AddSingleton(options);
services.AddHostedService<Worker>();
});
}
}
这里是 appsettings.json 文件(appsettings.Development.json)。
{
"PostConfig": {
"BaseFolder": "./App_Data/",
"LogsFolder": "logs/",
"SystemFQN": "C:/Test/PostalDB/PostalData.db",
"CustFQN": "C:/Test/PostalDB/PostalCustomer.db",
"LogFname": "USPS_.log",
"LogTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff}\t{EnvironmentUserName}\t[{Level:u4}]\t<{ThreadId}>\t{Message:lj}{NewLine}{Exception}"
}
}
我曾尝试在配置生成器中使用 .AddEnvironmentVariables(),但似乎没有改变事情。 我怀疑是因为明确调用了 addjsonfile。
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", true, true);
? - Guru Stron