Accessing the IHostingEnvironment in ConfigureServices method
Asked Answered
D

6

112

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.

Demobilize answered 6/6, 2016 at 14:28 Comment(1)
Does this answer your question? How to get the Development/Staging/production Hosting Environment in ConfigureServicesMauney
S
140

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

Sparoid answered 6/6, 2016 at 14:32 Comment(5)
Even though the new project templates for Asp.Net Core 2.0 don't include the parameter "IHostingEnvironment env" in the Startup constructor, it can be specified and it will be properly injected.Salford
Why in ConfigureServices it is impossible?Diseased
@Alexsandro_xpt to document the answer to your question on ConfigureServices, it's impossible because the framework doesn't support Dependency Injection for that particular method the way it does in other areas (probably because you use this method to configure dependency injection). Setting at the constructor level as Joe described should work around the issue.Acknowledge
@MarkG Unfortunately that answer is deleted... the its Q having been marked as a duplicate of this one. So including here...Buttermilk
As of .NET 5 IHostingEnvironment is deprecated and you'll want to use IWebHostEnvironment instead.Stannic
B
37

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
}
Buttermilk answered 6/6, 2016 at 14:28 Comment(5)
Hi, it's not a big deal but in the string formatting the environment is lower case, whereas the property seems to be Environment.Demission
@BenSmith I believe you have a typo. You repeated IHostingEnvironment in your statement "IHostingEnvironment is now obsolete and IHostingEnvironment should be used instead. What is the correct replacement for IHostingEnvironment?Bellina
Doh! Good spot @Blake. I'll delete my previous comment. My comment should've read "IHostingEnvironment is now obsolete, IWebHostEnvironment should be used instead".Casta
And to be extra clear, shouldn't it be said that IHostingEnvironment is only obsolete as of .Net Core 3.0? (I'm working on a 'take home test' that calls services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); inside the ConfigureServices() method and IHostingEnvironment is working fine.Sandisandidge
@ScottFraley correct. As this question and answer comes from the .NET Core 2.x time-frame (which a lot of projects will continue to be using for quite some time) it does still apply.Buttermilk
O
5

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...

Oppen answered 6/8, 2020 at 4:3 Comment(0)
N
2

If you don't have a Startup class (you may be creating a service) you can get the environment from the hostContext in ConfigureServices like so:

 public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureServices((hostContext, services) =>
                {
                    IConfiguration config = hostContext.Configuration;
                    Configuration = config;

                    var env = hostContext.HostingEnvironment;
                    EnvironmentName = env?.EnvironmentName;

...
Naturalism answered 28/1, 2021 at 9:19 Comment(0)
I
1

If you aren't using a Startup class and are calling .Configure() directly, you can access the IHostingEnvironment or IWebHostEnvironment using GetService:

ASP.NET Core 2.2:

.Configure(app => {
    var hostingEnvironment = app.ApplicationServices.GetService<IHostingEnvironment>();
    if (hostingEnvironment?.IsDevelopment() == true)
    {
        app.UseDeveloperExceptionPage();
    }

    // .. Other stuff
});

ASP.NET Core 3.x:

.Configure(app => {
    var hostingEnvironment = app.ApplicationServices.GetService<IWebHostEnvironment>();
    if (hostingEnvironment?.IsDevelopment() == true)
    {
        app.UseDeveloperExceptionPage();
    }

    // .. Other stuff
});
Inspan answered 23/9, 2020 at 1:27 Comment(0)
C
1

There are some examples here but none of them seem accurate to the newest release of dotnet, so here we go.

First, in your Startup.cs you should have a reference in your initial constructor like this:

public Startup(IConfiguration configuration, IWebHostEnvironment env)
        {
            this.Configuration = configuration;
            this.Environment = env;
        }

We can take the Env and tack it onto ServiceCollection like so:

services.AddSingleton(sp => this.Environment);

Then we can access it in any extension method or other place like so:

var hostEnvironment = services.BuildServiceProvider().GetRequiredService<IHostEnvironment>();

if (hostEnvironment.IsDevelopment())
   {
   //do something if in dev
   }
Conjoin answered 6/12, 2022 at 19:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.