{"id":1303,"date":"2018-01-16T11:00:24","date_gmt":"2018-01-16T09:00:24","guid":{"rendered":"http:\/\/tpodolak.com\/blog\/?p=1303"},"modified":"2018-01-16T01:26:47","modified_gmt":"2018-01-15T23:26:47","slug":"asp-net-core-passing-command-line-arguments-startup-class","status":"publish","type":"post","link":"https:\/\/tpodolak.com\/blog\/2018\/01\/16\/asp-net-core-passing-command-line-arguments-startup-class\/","title":{"rendered":"ASP.NET Core &#8211; passing command-line arguments to Startup class"},"content":{"rendered":"<h3>1. Introduction <\/h3>\n<p>I usually pass configuration to my web API via JSON files, but recently I needed to pass them also via command-line arguments. As the solution for <i>ASP.NET Core 2.x<\/i> is quite different than for <i>ASP.NET Core 1.x<\/i> I decided to describe both methods in here.<\/p>\n<h3>2. ASP.NET Core 2.x <\/h3>\n<p>For the newest version of <i>ASP.NET Core<\/i>, the solution is pretty straightforward as <i>IConfiguration<\/i> is injected by default to the <i>Startup<\/i> class. All we have to do is to add <i>CommandLineConfigurationSource<\/i> to <i>IConfigurationBuilder<\/i> when configuring <i>IWebHost<\/i>. <i>CommandLineConfigurationSource<\/i> is part of the <i>Microsoft.Extensions.Configuration.CommandLine<\/i> package and can be easily used by <i>AddCommandLine<\/i> extension method<\/p>\n<pre lang=\"csharp\">\r\npublic class Program\r\n{\r\n    public static void Main(string[] args)\r\n    {\r\n        BuildWebHost(args).Run();\r\n    }\r\n\t\r\n    public static IWebHost BuildWebHost(string[] args)\r\n    {\r\n        var webHost = new WebHostBuilder()\r\n\t     .UseKestrel()\r\n\t     .UseContentRoot(Directory.GetCurrentDirectory())\r\n\t     .ConfigureAppConfiguration((hostingContext, config) =>\r\n\t     {\r\n\t         var env = hostingContext.HostingEnvironment;\r\n\t         config.AddJsonFile(\"appsettings.json\", optional: true, reloadOnChange: true)\r\n\t               .AddJsonFile($\"appsettings.{env.EnvironmentName}.json\", optional: true, reloadOnChange: true);\r\n\t         config.AddEnvironmentVariables();\r\n\t         config.AddCommandLine(args);\r\n\t     }).UseStartup<Startup>()\r\n\t       .Build();\r\n        return webHost;\r\n    }\r\n}\r\n<\/pre>\n<p>Now we can access our command-line arguments just like any other configuration<\/p>\n<pre lang=\"csharp\">\r\npublic class Startup\r\n{\r\n    private readonly IConfiguration _configuration;\r\n\r\n    public Startup(IConfiguration configuration)\r\n    {\r\n        _configuration = configuration;\r\n    }\r\n\r\n    \/\/ This method gets called by the runtime. Use this method to add services to the container.\r\n    public void ConfigureServices(IServiceCollection services)\r\n    {\r\n        services.AddMvc();\r\n    }\r\n\r\n    \/\/ This method gets called by the runtime. Use this method to configure the HTTP request pipeline.\r\n    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IApplicationLifetime applicationLifetime)\r\n    {\r\n        loggerFactory.AddConsole();\r\n        loggerFactory.AddDebug();\r\n        applicationLifetime.ApplicationStarted.Register(() => loggerFactory.CreateLogger<Startup>().LogInformation(\"CommandLine argument {0}: \", _configuration[\"usecustomschema\"]));\r\n        if (env.IsDevelopment())\r\n        {\r\n            app.UseDeveloperExceptionPage();\r\n        }\r\n\r\n        app.UseMvc();\r\n    }\r\n}\r\n<\/pre>\n<p><a href=\"\/\/tpodolak.com\/blog\/wp-content\/uploads\/2018\/01\/asp-net-core-passing-command-line-arguments-to-startup-class\/AspNetCore2CommandLineArgument-1.png\"><img decoding=\"async\" src=\"\/\/tpodolak.com\/blog\/wp-content\/uploads\/2018\/01\/asp-net-core-passing-command-line-arguments-to-startup-class\/AspNetCore2CommandLineArgument-1.png\" alt=\"\" height=\"274\" class=\"aligncenter size-full wp-image-1306\" srcset=\"https:\/\/tpodolak.com\/blog\/wp-content\/uploads\/2018\/01\/asp-net-core-passing-command-line-arguments-to-startup-class\/AspNetCore2CommandLineArgument-1.png 653w, https:\/\/tpodolak.com\/blog\/wp-content\/uploads\/2018\/01\/asp-net-core-passing-command-line-arguments-to-startup-class\/AspNetCore2CommandLineArgument-1-150x63.png 150w, https:\/\/tpodolak.com\/blog\/wp-content\/uploads\/2018\/01\/asp-net-core-passing-command-line-arguments-to-startup-class\/AspNetCore2CommandLineArgument-1-300x126.png 300w\" sizes=\"(max-width: 653px) 100vw, 653px\" \/><\/a><\/p>\n<h3>3. ASP.NET Core 1.x <\/h3>\n<p>The solution for <i>ASP.NET Core 1.x<\/i> requires a bit more work but it is possible to achieve the same result. We still will be using <i>CommandLineConfigurationSource<\/i> from <i>Microsoft.Extensions.Configuration.CommandLine<\/i> package, however this time we have to manually create <i>IConfiguration<\/i> object and register it in the container before the <i>Startup<\/i> class is created. This is possible because the <i>WebHostBuilder<\/i> exposes <i>ConfigureServices<\/i> method.<\/p>\n<pre lang=\"csharp\">\r\npublic class Program\r\n{\r\n    public static void Main(string[] args)\r\n    {\r\n        var host = new WebHostBuilder()\r\n             .UseKestrel()\r\n             .UseContentRoot(Directory.GetCurrentDirectory())\r\n             UseIISIntegration()\r\n             .ConfigureServices(serviceCollection =>\r\n                 serviceCollection.AddSingleton<IConfiguration>(new ConfigurationBuilder().AddCommandLine(args).Build()))\r\n             .UseStartup<Startup>()\r\n             .Build();\r\n\r\n          host.Run();\r\n    }\r\n}\r\n<\/pre>\n<p>Having our service registered now we can easily access <i>IConfiguration<\/i> object in our application<\/p>\n<pre lang=\"csharp\">\r\npublic class Startup\r\n{\r\n    \/\/ This method gets called by the runtime. Use this method to add services to the container.\r\n    public void ConfigureServices(IServiceCollection services)\r\n    {\r\n        \/\/ Add framework services.\r\n        services.AddMvc();\r\n    }\r\n\r\n    \/\/ This method gets called by the runtime. Use this method to configure the HTTP request pipeline.\r\n    public void Configure(IApplicationBuilder app, IHostingEnvironment hostingEnvironment, IConfiguration configuration, ILoggerFactory loggerFactory, IApplicationLifetime applicationLifetime)\r\n    {\r\n        loggerFactory.AddConsole();\r\n        loggerFactory.AddDebug();\r\n        applicationLifetime.ApplicationStarted.Register(() =>\r\n                loggerFactory.CreateLogger<Startup>().LogInformation(\"CommandLine argument {0}: \", configuration[\"usecustomschema\"]));\r\n\r\n        if (hostingEnvironment.IsDevelopment())\r\n        {\r\n            app.UseDeveloperExceptionPage();\r\n        }\r\n\r\n        app.UseMvc();\r\n    }\r\n}\r\n<\/pre>\n<p><a href=\"\/\/tpodolak.com\/blog\/wp-content\/uploads\/2018\/01\/asp-net-core-passing-command-line-arguments-to-startup-class\/AspNetCoreCommandLineArgument-1.png\"><img decoding=\"async\" src=\"\/\/tpodolak.com\/blog\/wp-content\/uploads\/2018\/01\/asp-net-core-passing-command-line-arguments-to-startup-class\/AspNetCoreCommandLineArgument-1.png\" alt=\"\" width=\"674\" class=\"aligncenter size-full wp-image-1307\" srcset=\"https:\/\/tpodolak.com\/blog\/wp-content\/uploads\/2018\/01\/asp-net-core-passing-command-line-arguments-to-startup-class\/AspNetCoreCommandLineArgument-1.png 674w, https:\/\/tpodolak.com\/blog\/wp-content\/uploads\/2018\/01\/asp-net-core-passing-command-line-arguments-to-startup-class\/AspNetCoreCommandLineArgument-1-150x48.png 150w, https:\/\/tpodolak.com\/blog\/wp-content\/uploads\/2018\/01\/asp-net-core-passing-command-line-arguments-to-startup-class\/AspNetCoreCommandLineArgument-1-300x95.png 300w\" sizes=\"(max-width: 674px) 100vw, 674px\" \/><\/a><br \/>\nSource code for this post can be found <a href=\"https:\/\/github.com\/tpodolak\/Blog\/tree\/master\/AspNetCorePassingCommandLineArgumentsToStartupClass\">here<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>1. Introduction I usually pass configuration to my web API via JSON files, but recently I needed to pass them also via command-line arguments. As the solution for ASP.NET Core 2.x is quite different than for ASP.NET Core 1.x I decided to describe both methods in here. 2. ASP.NET Core 2.x For the newest version [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[317],"tags":[318],"class_list":["post-1303","post","type-post","status-publish","format-standard","hentry","category-asp-net-core","tag-asp-net-core"],"_links":{"self":[{"href":"https:\/\/tpodolak.com\/blog\/wp-json\/wp\/v2\/posts\/1303","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/tpodolak.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/tpodolak.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/tpodolak.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/tpodolak.com\/blog\/wp-json\/wp\/v2\/comments?post=1303"}],"version-history":[{"count":4,"href":"https:\/\/tpodolak.com\/blog\/wp-json\/wp\/v2\/posts\/1303\/revisions"}],"predecessor-version":[{"id":1311,"href":"https:\/\/tpodolak.com\/blog\/wp-json\/wp\/v2\/posts\/1303\/revisions\/1311"}],"wp:attachment":[{"href":"https:\/\/tpodolak.com\/blog\/wp-json\/wp\/v2\/media?parent=1303"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/tpodolak.com\/blog\/wp-json\/wp\/v2\/categories?post=1303"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/tpodolak.com\/blog\/wp-json\/wp\/v2\/tags?post=1303"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}