.NET Core 2.0控制台应用程序的配置

35

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

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

这使我们得到了 Configuration 对象,然后我们可以在控制台应用程序中使用它。

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

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

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


2
我认为它并没有改变。我认为.NET Core 1和.NET Core 2之间没有区别,即使在ASP.NET Core中也没有改变。他们只是定义了一个新方法 WebHost(CreateDefaultBuilder)来封装默认日志记录和配置设置。 - Jehof
3
Microsoft.Extensions.Configuration是一个独立的软件包。虽然它由ASP.NET团队维护,但它不依赖于ASP.NET。您可以在任何.NET Standard平台上使用ConfigurationBuilder - Jeroen Mostert
2个回答

35

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

ConfigurationBuilder位于自己的包中,就像Jeroen Mostert所说的那样。

但是请确保您还安装了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:找不到配置文件'appsettings.json',并且不是可选的。 物理路径为'LocalPathToProjectRedacted\bin\Debug\netcoreapp2.0\appsettings.json'。 appsettings文件位于我的项目根目录中。不确定如何解决它。 - Treeline
@Treeline,你应该将那个文件添加到你的.csproj目标中,就像我在最后一次编辑中所添加的那样。 - BillHaggerty
3
我通过在VS2017中启用“复制到输出目录”设置来使它工作。我将其设置为“始终复制”。现在,.csproj文件中有这个代码:<ItemGroup> <None Update="appsettings.json"> <CopyToOutputDirectory>Always</CopyToOutputDirectory> </None> </ItemGroup> 它可以完美地运行。 - Treeline
1
@treeline 在我的情况下,通过在添加JSON文件之前设置基本路径来使其工作:IConfiguration config = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile(fileName, false, true).Build(); - Henning Klokkeråsen
@HenningKlokkeråsen,你是怎么得到SetbasePath的?我一直在收到这个错误:ConfigurationBuilder没有SetBasePath的定义。 - Victor.Uduak
在添加了 Microsoft.Extensions.Configuration (2.1.1) 和 Microsoft.Extensions.Configuration.Json (2.1.1) 后,它可以正常工作。 - Victor.Uduak

10
在Program.cs中存储一个private static IServiceProvider provider;,然后在Main()方法中设置配置,就像您在aps.net core中一样。然后在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>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接