访问ConfigureServices方法中的IHostingEnvironment

时间:2016-06-06 14:28:30

标签: asp.net-core

我需要检查ConfigureServices方法当前的托管环境名称是否为'开发'。

因此使用IHostingEnvironment.IsDevelopment()方法对我来说可能没问题,但与Configure方法不同,我没有IHostingEnvironment env

5 个答案:

答案 0 :(得分:92)

只需在Startup类中创建一个属性即可保留IHostingEnvironment。在已有访问权限的Startup构造函数中设置该属性,然后可以从ConfigureServices

访问该属性

答案 1 :(得分:5)

从问题marked as duplicate of this one and deleted复制到此处。归功于a-ctor

如果您想在@import url('https://use.fontawesome.com/releases/v5.7.2/css/all.css'); 中访问IHostingEnvironment,则必须通过构造函数注入它,并将其存储以供以后在ConfigureServices中访问:

ConfigureServices

答案 2 :(得分:4)

IHostingEnvironment在Core 3.1中已弃用

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

应该做到这一点...

然后使用_env.IsDevelopment()等在任何地方进行引用...

答案 3 :(得分:0)

如果您不使用Startup类,而是直接调用.Configure(),则可以使用IHostingEnvironment访问IWebHostEnvironmentGetService

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
});

答案 4 :(得分:0)

如果您没有 Startup 类(您可能正在创建一个服务),您可以从 ConfigureServices 中的 hostContext 获取环境,如下所示:

 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;

...