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>();
});
});
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With