繁体   English   中英

.Net 6.0 配置文件

[英].Net 6.0 Configuration files

得到了一个应用程序,它为 VBA 应用程序提供数据。 现在尝试获取配置文件(appsettings.json & appsettings.Development.Json)。 现在它是一个 .net6.0 控制台应用程序,后来我将它变成了一个 IconTrayApp。

遇到一个问题,主 Program.cs 方法获取 appsettings.json,worker 获取 appsettings.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 调用。

您的主应用程序(主应用程序- 1st )使用任何appsettings.json并且您需要在被调用的控制台应用程序(辅助应用程序 - 2nd )中使用相同的文件。

您可以使用 args 调用第二个

1. 主程序的设置文件
例如位于“C:\appsettings.json”

{
  "AppName": "Value from main/primary/1st program AppSettings.json"
}

2.从主程序调用
您可以使用 arg SettingsFile发送任何文件名

dotnet.\CommandLineArgs.dll --SettingsFile=C:\appsettings.json
或者
.\CommandLineArgs.exe --SettingsFile=C:\appsettings.json

3. 二级程序代码

public class Program
{
    public static void Main(string[] args)
    {
        var builder = new ConfigurationBuilder()
            .AddJsonFile(args.Where(a => a.Contains("SettingsFile")).First().Split("=")[1], optional: false, reloadOnChange: true);
        IConfiguration config = builder.Build();
        Console.WriteLine(config.GetValue<string>("AppName"));
        Console.ReadLine();
    }
}

Output
模拟 powershell 是主程序。 Primary将值为C:\appsettings.json的 arg SettingsFile发送到Secondary 辅助程序将 json 文件名添加到配置生成器并构建配置 object。

1

2

参考

Main() 和命令行 arguments
命令行 arguments

我可能有点不清楚,工人得到了 appsettings.Development.json 文件,因为我在 VS 中运行是正确的。 我正在寻找的是一种在 Main() 方法中获得相同行为的干净方法。

我接受了 Guru Stron 的评论并强制它包含 appsettings.dev... 文件,如下所示:

      var builder = new ConfigurationBuilder()
        .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
        .AddJsonFile($"appsettings.{Environments.Development}.json", optional: true, reloadOnChange: true);

它似乎工作正常,只是感觉我在硬编码应该被烘焙的东西。

Also if I run the application from the Windows File Explorer I get the appsettings.developement.json values in the main but the appsettings.json in the worker class. 这是有意义的,因为每个构建器调用的文件 appsettings.development.json 会覆盖 appsettings.json。 不理想。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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