Accessing the IHostingEnvironment in ConfigureServices method

I need to check in ConfigureServices method whether the current hosting environment name is 'Development'.

So using IHostingEnvironment.IsDevelopment() method may be ok for me, but unlike in Configure method, I do not have IHostingEnvironment env.


Solution 1:

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

Solution 2:

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
}