简体   繁体   English

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

[英]Configuration for console apps .net Core 2.0

In .net Core 1 we could do this: 在.net Core 1中我们可以这样做:

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

And that gave use the Configuration object that we could then use in our console app. 这使我们可以在我们的控制台应用程序中使用Configuration对象。

All examples for .net core 2.0 seem to be tailored to the new way Asp.Net core config is created. .net core 2.0的所有示例似乎都是针对Asp.Net核心配置创建的新方式而定制的。

What is the way to create configurations for console apps? 为控制台应用程序创建配置的方法是什么?

Update: this question is not related to Asp.net core. 更新:此问题与Asp.net核心无关。 Please do not add asp.net core tags when editing. 编辑时请不要添加asp.net核心标记。

It seems there is no change, as Jehof says. 正如杰霍夫所说,似乎没有变化。

ConfigurationBuilder is in its own package, as Jeroen Mostert says. 正如Jeroen Mostert所说,ConfigurationBuilder在它自己的包中。

But make sure you also have the Microsoft.Extensions.Configuration.Json package, where the .AddJsonFile() extension lives. 但请确保您还有.AddJsonFile()扩展所在的Microsoft.Extensions.Configuration.Json包。

In summary, you need the following two NuGet packages: 总之,您需要以下两个NuGet包:

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

Store a private static IServiceProvider provider; 存储private static IServiceProvider provider; in your Program.cs. 在你的Program.cs中。 Then Setup the configuration just like you would in aps.net core but of course you would do it in Main(). 然后像在aps.net核心中一样设置配置,但当然你会在Main()中进行。 Then Configure each section inside your IServiceProvider. 然后配置IServiceProvider中的每个部分。 This way you can use the constructor dependency injection. 这样您就可以使用构造函数依赖注入。 Also note that I have two configurations in my watered down example. 另请注意,我的淡化示例中有两个配置。 One contains secrets that should be kept out of source control and stored outside of the project structure, and I have AppSettings which contains standard configuration settings that don't need to be kept private.(It is important!) 一个包含应该保留在源代码控制之外并存储在项目结构之外的秘密,我有AppSettings,其中包含不需要保密的标准配置设置。(这很重要!)

When you want to use the config then you can take it out of the provider, or pull an object out of the provider that uses your settings classes in their constructors. 如果要使用配置,则可以将其从提供程序中取出,或将对象从提供程序中拉出来,这些提供程序在其构造函数中使用您的设置类。

    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());
     }

these are the dependencies I recommend starting out with when making a dotnetcore cli app. 这些是我建议在制作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" />

Also note that you will need to copy your settings to your publish and build directories. 另请注意,您需要将设置复制到发布和构建目录。 You can do that by adding targets to your csproj file. 您可以通过向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>

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

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