net core console app how to use appsettings.json code example
Example 1: use appsettings.json in console app
All that’s required is to add the following NuGet packages and an appsettings.json file.
Microsoft.Extensions.Configuration
Microsoft.Extensions.Configuration.FileExtensions
Microsoft.Extensions.Configuration.Json
The appsettings.json files “Copy to Output Directory” property should also be set to “Copy if newer” so that the application is able to access it when published.
Example 2: .net core read appsettings.json console app
class Program
{
public static IConfigurationRoot configuration;
static int Main(string[] args)
{
Log.Logger = new LoggerConfiguration()
.WriteTo.Console(Serilog.Events.LogEventLevel.Debug)
.MinimumLevel.Debug()
.Enrich.FromLogContext()
.CreateLogger();
try
{
MainAsync(args).Wait();
return 0;
}
catch
{
return 1;
}
}
static async Task MainAsync(string[] args)
{
Log.Information("Creating service collection");
ServiceCollection serviceCollection = new ServiceCollection();
ConfigureServices(serviceCollection);
Log.Information("Building service provider");
IServiceProvider serviceProvider = serviceCollection.BuildServiceProvider();
Console.WriteLine(configuration.GetConnectionString("DataConnection"));
try
{
Log.Information("Starting service");
await serviceProvider.GetService<App>().Run();
Log.Information("Ending service");
}
catch (Exception ex)
{
Log.Fatal(ex, "Error running service");
throw ex;
}
finally
{
Log.CloseAndFlush();
}
}
private static void ConfigureServices(IServiceCollection serviceCollection)
{
serviceCollection.AddSingleton(LoggerFactory.Create(builder =>
{
builder
.AddSerilog(dispose: true);
}));
serviceCollection.AddLogging();
configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetParent(AppContext.BaseDirectory).FullName)
.AddJsonFile("appsettings.json", false)
.Build();
serviceCollection.AddSingleton<IConfigurationRoot>(configuration);
serviceCollection.AddTransient<App>();
}
}