【问题标题】:Configuration for console apps .net Core 2.0控制台应用程序 .net Core 2.0 的配置
【发布时间】:2018-11-24 22:08:36
【问题描述】:

在 .net Core 1 中我们可以这样做:

IConfiguration config =  new ConfigurationBuilder()
                .AddJsonFile("appsettings.json", true, true)
                .Build();

这让我们可以在控制台应用程序中使用配置对象。

.net core 2.0 的所有示例似乎都是针对创建 Asp.Net 核心配置的新方式量身定制的。

为控制台应用程序创建配置的方法是什么?

更新:这个问题与 Asp.net 核心无关。编辑时请不要添加asp.net core标签。

【问题讨论】:

  • 我会说它保持不变。我认为 .net core 1 和 .net core 2 之间没有区别。即使在 asp.net-core 中也没有变化。他们只在 WebHost (CreateDefaultBuilder) 上定义了一个新方法来封装默认的日志记录和配置设置。
  • Microsoft.Extensions.Configuration 是它自己的包。虽然它由 ASP.NET 人员维护,但它不依赖于 ASP.NET。您可以在任何 .NET Standard 平台中使用 ConfigurationBuilder

标签: c# .net-core .net-core-2.0


【解决方案1】:

正如 Jehof 所说,似乎没有任何变化。

正如 Jeroen Mostert 所说,ConfigurationBuilder 在它自己的包中。

但请确保您还有 Microsoft.Extensions.Configuration.Json 包,其中 .AddJsonFile() 扩展名存在。

总的来说,你需要以下两个 NuGet 包:

  • Microsoft.Extensions.Configuration (2.0.0)
  • Microsoft.Extensions.Configuration.Json (2.0.0)

【讨论】:

  • 我和@zaitsman 有同样的问题。我的配置看起来与他的示例相同,除了我没有将 json 文件标记为可选。但即使包含您提到的 nuget 包,我似乎也无法访问我的设置文件。我收到此错误:System.IO.FileNotFoundException : The configuration file 'appsettings.json' was not found and is not optional. The physical path is 'LocalPathToProjectRedacted\bin\Debug\netcoreapp2.0\appsettings.json'. appsettings 文件位于我项目的根目录中。不知道如何解决。
  • @Treeline 您应该将该文件作为目标添加到您的 .csproj 中,就像我在上次编辑中添加到我的答案中一样。
  • 我通过在 VS2017 中为文件启用“复制到输出目录”设置来使其工作。我将其设置为“始终复制”。 .csproj 现在有这个:<ItemGroup> <None Update="appsettings.json"> <CopyToOutputDirectory>Always</CopyToOutputDirectory> </None> </ItemGroup>,它可以完美运行。
  • @treeline 它适用于我通过在添加 JSON 文件之前设置基本路径:IConfiguration config = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile(fileName, false, true).Build();;
  • @HenningKlokkeråsen 您是如何获得 SetbasePath 的?收到此错误 ConfigurationBuilder 不包含 SetBasePath 的定义
【解决方案2】:

在您的 Program.cs 中存储 private static IServiceProvider provider;。然后像在 aps.net core 中一样设置配置,当然你可以在 Main() 中进行。然后在您的 IServiceProvider 中配置每个部分。这样你就可以使用构造函数依赖注入。另请注意,在我的淡化示例中有两种配置。一个包含应该远离源代码控制并存储在项目结构之外的秘密,我有 AppSettings,其中包含不需要保密的标准配置设置。(这很重要!)

当您想使用配置时,您可以将其从提供程序中取出,或者从提供程序中提取一个对象,该对象在其构造函数中使用您的设置类。

    private static IServiceProvider provider;
    private static EventReceiver receiver;
    static void Main(string[] args)
    {
        IConfigurationRoot config = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile(path: "/opt/Secrets.json", optional: false, reloadOnChange: true)
            .AddJsonFile(path: "AppSettings.json", optional: false, reloadOnChange: true)
            .Build();
        provider = new ServiceCollection()
            .AddSingleton<CancellationTokenSource>()
            .Configure<Settings>(config.GetSection("SettingsSection"))
            .BuildServiceProvider();
        receiver = new EventReceiver<Poco>(ProcessPoco);
        provider.GetRequiredService<CancellationTokenSource>().Token.WaitHandle.WaitOne();
    }

    private static void ProcessPoco(Poco poco)
    {
        IOptionsSnapshot<Settings> settings = provider.GetRequiredService<IOptionsSnapshot<Settings>>();
        Console.WriteLine(settings.ToString());
     }

这些是我建议在制作 dotnetcore cli 应用程序时开始使用的依赖项。

<PackageReference Include="Microsoft.Extensions.Configuration" Version="2.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="2.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="2.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="2.0.0" />
<PackageReference Include="microsoft.extensions.logging.abstractions" Version="2.0.0" />

另请注意,您需要将设置复制到发布和构建目录。您可以通过将目标添加到您的 csproj 文件来做到这一点。

  <Target Name="CopyToOut" BeforeTargets="BeforeBuild">
    <Copy SourceFiles="../ProjPath/AppSettings.json" DestinationFolder="$(TargetDir)" SkipUnchangedFiles="true" />
  </Target>
  <Target Name="CopyToOutOnPublish" AfterTargets="Publish">DestinationFolder="$(PublishDir)" SkipUnchangedFiles="true" />
    <Copy SourceFiles="../ProjPath/AppSettings.json" DestinationFolder="$(PublishDir)" SkipUnchangedFiles="true" />
  </Target>

【讨论】:

    猜你喜欢
    • 2016-11-02
    • 2016-12-07
    • 1970-01-01
    • 1970-01-01
    • 2018-09-12
    • 1970-01-01
    • 1970-01-01
    • 2018-02-08
    • 2018-05-28
    相关资源
    最近更新 更多