c# appsettings.json code example
Example 1: appsettings in console application c#
public Startup()
{
var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{environment}.json", optional: true)
.AddEnvironmentVariables()
.Build();
}
Example 2: .net using appsettings variables
var connectionString = ConfigurationManager.ConnectionStrings["Default"].ConnectionString;
connectionString.Expand()
Example 3: appsettings in console application c#
using System;
using Microsoft.Extensions.Configuration;
namespace DiConsoleApp
{
public class SomeService : ISomeService
{
IConfiguration configuration;
public SomeService(IConfiguration configuration)
{
this.configuration = configuration;
}
public void DoProcess()
{
var value = configuration["SomeKey"];
Console.WriteLine("Value from the Config is: " + value);
}
}
}
Example 4: .net using appsettings variables
<configuration>
<appSettings>
<add key="Domain" value="mycompany.com"/>
<add key="ServerName" value="db01.{Domain}"/>
</appSettings>
<connectionStrings>
<add name="Default" connectionString="server={ServerName};uid=uid;pwd=pwd;Initial Catalog=master;" provider="System.Data.SqlClient" />
</connectionStrings>
</configuration>
Example 5: .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>();
}
}