How to access IHostingEnvironment, ContentRoot inside Program.cs Main method?

Viewed 888

I need to access IHostingEnvironment.ContentRootPath inside Program.cs -> Main method. I followed some answers from the internet but nothing comes to my rescue.

My code looks like the following; i can declare a variable inside the Main method of type IHostingEnvironment but i am not sure what should i initialize it with.

public static void Main(string[] args)
{
    IHostingEnvironment env;
}
1 Answers

You can get it from host object:

public static void Main(string[] args)
{
    var builder = CreateHostBuilder(args);
    var host = builder.Build();
    var hostingEnvironment = host.Services.GetService(typeof(IHostingEnvironment));

    host.Run();
}

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
        });
Related