78

I try to create a .NET 6 Console Application but having troubles reading my appsettings.json file. In a web application I could use this...

var builder = WebApplication.CreateBuilder(args);

But what would I use in a console application? I get this error when trying to add it to program.cs. "The name 'WebApplication' does not exist in the current context"

7

9 Answers 9

99

Add these two nuget packages in your application

Microsoft.Extensions.Configuration

Microsoft.Extensions.Configuration.Json

Then you can use ConfigurationBuilder to use appsettings.json file

var configuration =  new ConfigurationBuilder()
     .AddJsonFile($"appsettings.json");
            
var config = configuration.Build();
var connectionString = config.GetConnectionString("ConnectionString");

Getting Values from AppSettings in Console Application

Adding AppSettings in .net core app

Sign up to request clarification or add additional context in comments.

6 Comments

I tried your approach but that does not work. I get "The name 'builder' does not exist in the current context" error?
It will be configuration.Build(); I corrected it in my code
Don't forget to include appsettings.json when building (Properties -> Copy to Output Directory)
Don't need both nugets. Just Microsoft.Extensions.Configuration.Json because that package implicitly uses Microsoft.Extensions.Configuration already 😎
i have error: System.IO.FileNotFoundException: "The configuration file 'appsettings.json' was not found and is not optional. The expected physical path was 'C:\work\CheckerHistory\CheckerHistory\CheckerHistory\bin\Debug\net7.0\appsettings.json'." But including appsettings.json when building (Properties -> Copy to Output Directory) helps.
|
39

Link to docs: https://learn.microsoft.com/en-us/dotnet/core/extensions/configuration

Nuget packages are needed to do it:

<PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="6.0.0" />
    <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="6.0.0" />
    <PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="6.0.0" />

using Microsoft.Extensions.Configuration;

    // Build a config object, using env vars and JSON providers.
    IConfiguration config = new ConfigurationBuilder()
        .AddJsonFile("appsettings.json")
        .AddEnvironmentVariables()
        .Build();
    
    // Get values from the config, given their key and their target type.
    Settings settings = config.GetRequiredSection("Settings").Get<Settings>();
    
    // Write the values to the console.
    Console.WriteLine($"KeyOne = {settings.KeyOne}");
    Console.WriteLine($"KeyTwo = {settings.KeyTwo}");
    Console.WriteLine($"KeyThree:Message = {settings.KeyThree.Message}");

// Application code which might rely on the config could start here.
// This will output the following:
//   KeyOne = 1
//   KeyTwo = True
//   KeyThree:Message = Oh, that's nice...

JSON File (appsettings.json)

{
    "Settings": {
        "KeyOne": 1,
        "KeyTwo": true,
        "KeyThree": {
            "Message": "Oh, that's nice..."
        }
    }
}

UPD: I checked the approach, and it works; My code:

// See https://aka.ms/new-console-template for more information

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;

Console.WriteLine("Hello, World!");
ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
IConfiguration c = configurationBuilder.AddJsonFile("appsettings.json").AddEnvironmentVariables().Build();
var k = c.GetRequiredSection("Settings").Get<Settings>().KeyOne;
var n = 1;

public class NestedSettings
{
    public string Message { get; set; } = null!;
}
public class Settings
{
    public int KeyOne { get; set; }
    public bool KeyTwo { get; set; }
    public NestedSettings KeyThree { get; set; } = null!;
}




1 Comment

19

Using .NET 6 Console app, try:

using IHost host = Host.CreateDefaultBuilder(args).Build();

IConfiguration config = host.Services.GetRequiredService<IConfiguration>();

string con= config.GetValue<string>("ConnectionStrings:conn1");
//OR
string connectionString = config["ConnectionStrings:conn1"];

Console.WriteLine($"Hello, World! {connectionString}");

appsettings.json (Properties): (CopyToOutputDirectory = Always):

"ConnectionStrings": {
    "conn1": "Server=localhost;Database=MyDatabase;Trusted_Connection=True", 
  }

5 Comments

I am a little confused why this is accepted but unpopular, and how it doesn't reference the JSON file-name.
Also IMO secrets like this should not be contained in a json file (esp. if its checked into source control). This is what user secrets is for.
What is Host in desktop app or console app ?
@Mr.Boy I guess if you are also using Host.CreateApplicationBuilder() for dependency injection stuff, you can use this answer to get IConfiguration via: host.Services.GetRequiredService<IConfiguration>(). Otherwise you can use the other answer which uses ConfigurationBuilder instead.
7

In a console app I add the appsettings.json and user secrets like this, you may also have a development json file as well.

internal class Program
{
    internal static IConfigurationRoot Configuration;

    public static void Main()
        => new Program().MainAsync().GetAwaiter().GetResult();

    private async Task MainAsync()
    {
        var configurationBuilder = new ConfigurationBuilder();
        configurationBuilder.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
        configurationBuilder.AddUserSecrets(typeof(Program).GetTypeInfo().Assembly, optional: false);
        Configuration = configurationBuilder.Build();

        ...
    }
}

Then elsewhere in the console app in any class you can simply call it like this

var someSetting = Program.Configuration["SomeSetting"];

If you want a strongly typed class then see this answer .net core Console application strongly typed Configuration on SO

1 Comment

Main method supports async Task, my advice is to don't use GetAwaiter().GetResult()
4

I would prefer the following code because it will automatically read the appsettings.json file from the project directory. Pay attention to _.Configuration I used during configuring DbContext to read the connection string.

var builder = Host.CreateDefaultBuilder(args)
        .ConfigureServices(
                (_, services) => services
                    .AddTransient<IService, Service>()
                    .AddDbContext<ApplicationDbContext>(options =>
                        options.UseNpgsql(
                      _.Configuration.GetConnectionString("DefaultConnection"),
                            b => b.MigrationsAssembly(typeof(ApplicationDbContext).Assembly.FullName)))
                    );
var host = builder.Build();


var dbContext = host.Services.GetRequiredService<ApplicationDbContext>();

I put this together from this link: https://bjdejongblog.nl/net-core-6-dependency-injection-console-program/

1 Comment

How-to use configuration in library class dependencies?
1

Install the following packages

Install-Package Microsoft.Extensions.Configuration.Json
Install-Package Microsoft.Extensions.Hosting

create a file call appsettings.json

{
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "defaultConnection": "data source=.;initial catalog=ExchangeGatewayDb;integrated security=true;MultipleActiveResultSets=True;"
  }
}

add this code to Programe.cs

var hostBuilder = new HostBuilder().ConfigureHostConfiguration(config =>
        {
            config.AddEnvironmentVariables();

            if (args != null)
            {
                config.AddCommandLine(args);
            }
        }).ConfigureAppConfiguration((context, builder) =>
        {
            var env = context.HostingEnvironment;
            builder.SetBasePath(AppContext.BaseDirectory)
            .AddJsonFile("appsettings.json", optional: false)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true).AddEnvironmentVariables();

            var configuration = builder.Build();
            var connectionString = configuration["ConnectionStrings:defaultConnection"];
        }).ConfigureServices(services =>
        {
            services.Configure<ConsoleLifetimeOptions>(opts => opts.SuppressStatusMessages = true);
            //your code
        });

var buildHost = hostBuilder.Build();
buildHost.Run();

4 Comments

Tried this and the program is always stuck on buildHost.Run()
You should do your operation in the ConfigureServices method
If you make a new .net 6 console application there is no ConfigureServices-method.
@esko how-to use with net 6 console?
1

For console app, we should not use

WebApplication.CreateBuilder(args);

Instead, we should create builder by

var builder = new ConfigurationBuilder();

Add 2 Nuget packages,

  1. Microsoft.Extensions.Configuration.Json
  2. Microsoft.Extensions.Configuration.EnvironmentVariables

then access your app settings by following code,

var builder = new ConfigurationBuilder();
builder.SetBasePath(Directory.GetCurrentDirectory())
   .AddJsonFile("appsettings.json", optional: false, reloadOnChange: 
true);

if you want to override appsettings value by environment, you need to use following,

var builder = new ConfigurationBuilder();
    builder.SetBasePath(Directory.GetCurrentDirectory())
           .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
           .AddEnvironmentVariables("Jai_");

Comments

0

I use in my MyApp.Core library, in a ConfigMyApp class:

         public static IConfigurationRoot GetIConfigurationRoot(string outputPath = null)
        {
            var path1 = Directory.GetCurrentDirectory();
            //_configuration =
            var config = new ConfigurationBuilder()
                .SetBasePath(path1)
                .AddJsonFile("appsettings.json").Build();
            return config;
            //return new ConfigurationBuilder()
            //    .SetBasePath(outputPath)
            //    .AddJsonFile("appsettings.json", optional: true)
            //    //.AddUserSecrets("e3dfcccf-0cb3-423a-b302-e3e92e95c128")
            //    .AddEnvironmentVariables()
            //    .Build();
        }

        public static string CONEXION_SQL
        {
            get
            {
                var config = GetIConfigurationRoot();
                return config.GetConnectionString(KeyConexionMyApp);
                //return ConfigurationManager.ConnectionStrings[KeyConexionMyApp].ConnectionString;
            }
        }

Usage:

var myConnectionSQL = ConfigMyApp.CONEXION_SQL;

Use static constructor:

public static partial class ConfigMyApp
{
    static readonly IConfigurationRoot config;
    static ConfigMyApp()
    {
        config = GetIConfigurationRoot();
    }

Comments

0
  1. you need to create appSetting.json file and set Property Copy Output Directory - copy always

2.write code as below.

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using MidcapERP.Kafka.Configurations;
using MidcapERP.Kafka.Services;

await CreateHostBuilder(args).RunConsoleAsync();

static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
    .ConfigureLogging((hostContext, builder) =>
    {
        builder.ClearProviders(); // This line is optional if you want to clear the default logging providers
        builder.AddConfiguration(hostContext.Configuration.GetSection("Logging"));
        builder.AddConsole();
        builder.AddDebug();
        builder.AddEventSourceLogger();
        builder.SetMinimumLevel(LogLevel.Warning);
    })
    .ConfigureServices((hostContext, services) =>
    {
        services.AddOptions();
        services.Configure<KafkaConfiguration>(hostContext.Configuration.GetSection(nameof(KafkaConfiguration)));
        services.AddHostedService<KafkaConsumerService>();
    })
    .UseConsoleLifetime(); // This line should be the last one

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.