Configuration for console apps .net Core 2.0

20,519

Solution 1

It seems there is no change, as Jehof says.

ConfigurationBuilder is in its own package, as Jeroen Mostert says.

But make sure you also have the Microsoft.Extensions.Configuration.Json package, where the .AddJsonFile() extension lives.

In summary, you need the following two NuGet packages:

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

Solution 2

Store a private static IServiceProvider provider; in your Program.cs. Then Setup the configuration just like you would in aps.net core but of course you would do it in Main(). Then Configure each section inside your 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!)

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.

<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.

  <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>
Share:
20,519
zaitsman
Author by

zaitsman

All things iOS - Swift All things Salesforce - Lightning, APEX, API All things Marketing - SEO, Analytics, R All things EMM - encryption, enrollment, stateful systems, databases, APIs, identity

Updated on November 25, 2020

Comments

  • zaitsman
    zaitsman over 3 years

    In .net Core 1 we could do this:

    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.

    All examples for .net core 2.0 seem to be tailored to the new way Asp.Net core config is created.

    What is the way to create configurations for console apps?

    Update: this question is not related to Asp.net core. Please do not add asp.net core tags when editing.

  • Treeline
    Treeline over 6 years
    I have the same question as @zaitsman. My config looks the same as his example, except I have not marked the json file as optional. But even with the inclusion of the nuget packages you mention, I can't seem to access my settings file. I get this error: System.IO.FileNotFoundException : The configuration file 'appsettings.json' was not found and is not optional. The physical path is 'LocalPathToProjectRedacted\bin\Debug\netcoreapp2.0\appsetti‌​ngs.json'. The appsettings file is located at the root of my project. Not sure how to fix it.
  • BillHaggerty
    BillHaggerty over 6 years
    @Treeline you should add that file as a target in your .csproj like I added to my answer in my last edit.
  • Treeline
    Treeline over 6 years
    I got it working by enabling the "Copy to Output Directory" setting in VS2017 for the file. I set it to "Copy always". The .csproj now has this: <ItemGroup> <None Update="appsettings.json"> <CopyToOutputDirectory>Always</CopyToOutputDirectory> </None> </ItemGroup> and it works flawlessly.
  • Henning Klokkeråsen
    Henning Klokkeråsen over 6 years
    @treeline It works for my by setting base path before adding the JSON file: IConfiguration config = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile(fileName, false, true).Build();;
  • Victor.Uduak
    Victor.Uduak over 5 years
    @HenningKlokkeråsen how did you get SetbasePath? am getting this error ConfigurationBuilder does not contain a definition for SetBasePath
  • Victor.Uduak
    Victor.Uduak over 5 years
    It worked after adding Microsoft.Extensions.Configuration (2.1.1) Microsoft.Extensions.Configuration.Json (2.1.1)