ASP.NET Core 2 answer:
Change the default Program.cs to be:
using System;
using System.IO;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingContext, config) =>
{
config.SetBasePath(Directory.GetCurrentDirectory());
config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{hostingContext.HostingEnvironment.EnvironmentName}.json", optional: true, reloadOnChange: true);
config.AddEnvironmentVariables();
config.AddCommandLine(args);
})
.UseStartup<Startup>()
.Build();
}
I removed other bits just to make the configuration explanation easier.
Note the .AddCommandLine(args)
line in the configuration builder.
Unlike @BanksySan's answer you DON'T need to create a static property, instead let DI inject the IConfiguration into the startup class.
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
private IConfiguration Configuration { get; }
You can now use the configuration entries from any of the config providers, file, env variables and commandline.
Example:
dotnet run --seed true
public void Configure(IApplicationBuilder app)
{
app.UseExceptionHandler("/Home/Error");
var seed = Configuration.GetValue<bool>("seed");
if (seed)
SeedData.Initialize(app);
app.UseStaticFiles();
app.UseMvcWithDefaultRoute();
}
Hope this helps someone further.