访问ConfigureServices方法中的IHostingEnvironment

问题描述 投票:65回答:2

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

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

asp.net-core
2个回答
93
投票

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


6
投票

从问题marked as duplicate of this one and deleted复制到这里。感谢a-ctor

如果你想访问IHostingEnvironment中的ConfigureServices,你必须通过构造函数注入它并存储它以便以后访问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
}
© www.soinside.com 2019 - 2024. All rights reserved.