Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get environment variables from inside Main() in ASP.NET Core?

I want to know if the code is Dev/Stage so I need to get this. I tried the code below but it seems to skip running the Configure() of Startup.cs. Help ?

 public static void Main(string[] args)
        {
            IHost host = CreateHostBuilder(args).Build();

            SeedDatabase(host);

            host.Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args)
        {


            //return Host.CreateDefaultBuilder(args)
            //  .ConfigureWebHostDefaults(webBuilder =>
            //  {
            //      webBuilder.UseStartup<Startup>();
            //  });




            return Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();

                    webBuilder.ConfigureServices(services => { })
                    .Configure(app =>
                    {
                        Env = app.ApplicationServices.GetRequiredService<IWebHostEnvironment>();
                    });
                });
        }
like image 893
punkouter Avatar asked Dec 11 '22 00:12

punkouter


1 Answers

You haven't quite explained what it is you are trying to get (the environment variables or the environment object). But based on some of the code in the question it appears like you want access to the IWebHostEnvironment.

That's easy. IHost has a Services property. You just need to request the appropriate service.

IHost host = CreateHostBuilder(args).Build();
IWebHostEnvironment env = host.Services.GetRequiredService<IWebHostEnvironment>();
// now do something with env
SeedDatabase(host);
host.Run();

Now if you need the environment prior to everything else, you can also access the environment from the WebHostBuilderContext inside of a different overload of ConfigureServices:

webBuilder.ConfigureServices((ctx, services) => { 
   IWebHostEnvironment env = ctx.HostingEnvironment;
   // Do something with env
});

Similarly ConfigureAppConfiguration, ConfigureHostConfiguration and ConfigureServices on the IHostBuilder (the generic host) also provide access to the IHostEnvironment (note lack of "Web"):

return Host.CreateDefaultBuilder(args)
   .ConfigureAppConfiguration((ctx, config) => {
      IHostEnvironment env = ctx.HostingEnvironment;
   })
   .ConfigureServices((ctx, services) => {
      IHostEnvironment env = ctx.HostingEnvironment;
   })
   .ConfigureWebHostDefaults(/* etc */ );

The same service collection, environments etc are used by the generic host and the web host (in addition to the added IWebHostEnvironment)

Side note: Usually Startup.cs isn't invoked until the first call is made to your application. That is probably why it appears to not be running.

like image 102
pinkfloydx33 Avatar answered May 03 '23 07:05

pinkfloydx33