Accessing the IHostingEnvironment in ConfigureServices method

IHostingEnvironment is deprecated in Core 3.1

        private readonly IWebHostEnvironment _env;
   
        public Startup(IConfiguration configuration, IWebHostEnvironment env)
        {
            _env = env;
            Configuration = configuration;
        }

should do the trick...

Then reference anywhere with _env.IsDevelopment() etc...


just create a property in the Startup class to persist the IHostingEnvironment. Set the property in the Startup constructor where you already have access, then you can access the property from ConfigureServices


Copied here from question marked as duplicate of this one and deleted. Credit to a-ctor.

If you want to access IHostingEnvironment in ConfigureServices you will have to inject it via the constructor and store it for later access in ConfigureServices:

public class Startup
{
    public Startup(IConfiguration configuration, IHostingEnvironment environment)
    {
        Configuration = configuration;
        Environment = environment;
    }

    public IConfiguration Configuration { get; }

    public IHostingEnvironment Environment { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();

        System.Console.WriteLine($"app: {Environment.ApplicationName}");
    }

    // rest omitted
}

Tags:

Asp.Net Core