如何在启动中的ConfigureServices方法中获得开发/登台/生产托管环境?

public void ConfigureServices(IServiceCollection services)
{
    // Which environment are we running under?
}

ConfigureServices方法只接受一个IServiceCollection参数。


当前回答

在Dotnet Core 2.0中,启动构造函数只需要一个iconfigure -parameter。

    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

如何了解那里的托管环境? 我将它存储在ConfigureAppConfiguration期间的Program-class中 (使用完整的BuildWebHost而不是WebHost.CreateDefaultBuilder):

public class Program
{
    public static IHostingEnvironment HostingEnvironment { get; set; }

    public static void Main(string[] args)
    {
        // Build web host
        var host = BuildWebHost(args);

        host.Run();
    }

    public static IWebHost BuildWebHost(string[] args)
    {
        return new WebHostBuilder()
            .UseConfiguration(new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("hosting.json", optional: true)
                .Build()
            )
            .UseKestrel()
            .UseContentRoot(Directory.GetCurrentDirectory())
            .ConfigureAppConfiguration((hostingContext, config) =>
            {
                var env = hostingContext.HostingEnvironment;

                // Assigning the environment for use in ConfigureServices
                HostingEnvironment = env; // <---

                config
                  .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                  .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);

                if (env.IsDevelopment())
                {
                    var appAssembly = Assembly.Load(new AssemblyName(env.ApplicationName));
                    if (appAssembly != null)
                    {
                        config.AddUserSecrets(appAssembly, optional: true);
                    }
                }

                config.AddEnvironmentVariables();

                if (args != null)
                {
                    config.AddCommandLine(args);
                }
            })
            .ConfigureLogging((hostingContext, builder) =>
            {
                builder.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
                builder.AddConsole();
                builder.AddDebug();
            })
            .UseIISIntegration()
            .UseDefaultServiceProvider((context, options) =>
            {
                options.ValidateScopes = context.HostingEnvironment.IsDevelopment();
            })
            .UseStartup<Startup>()
            .Build();
    }

Ant然后像这样在ConfigureServices中读取它:

public IServiceProvider ConfigureServices(IServiceCollection services)
{
    var isDevelopment = Program.HostingEnvironment.IsDevelopment();
}

其他回答

另一种方法是使用configuration ["ASPNETCORE_ENVIRONMENT"]直接从配置中读取环境名称。这适用于任何可以访问配置的地方。

public IConfiguration Configuration { get; }

public Startup(IConfiguration configuration)
{
    Configuration = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
    Console.WriteLine(Configuration["ASPNETCORE_ENVIRONMENT"]);
}

前提条件是主机是用program .cs中的host . createdefaultbuilder()创建的,这是ASP. cs的默认值。NET Core 3.0(和5.0)web应用程序。如果使用其他构建器,则可以使用program .cs中的AddEnvironmentVariables()添加envars。

我想在我的服务中加入这种环境。这真的很容易做到!我只是像这样把它注入到构造函数中:

    private readonly IHostingEnvironment _hostingEnvironment;

    public MyEmailService(IHostingEnvironment hostingEnvironment)
    {
        _hostingEnvironment = hostingEnvironment;
    }

现在在稍后的代码中,我可以这样做:

if (_hostingEnvironment.IsProduction()) {
    // really send the email.
}
else {
    // send the email to the test queue.
}

编辑:

上面的代码是用于。net Core 2的。对于版本3,您将使用IWebHostEnvironment。

来自文档

Configure和ConfigureServices支持特定环境的版本 配置{EnvironmentName}和配置{EnvironmentName}形式的服务:

你可以这样做……

public void ConfigureProductionServices(IServiceCollection services)
{
    ConfigureCommonServices(services);
    
    //Services only for production
    services.Configure();
}

public void ConfigureDevelopmentServices(IServiceCollection services)
{
    ConfigureCommonServices(services);
    
    //Services only for development
    services.Configure();
}

public void ConfigureStagingServices(IServiceCollection services)
{
    ConfigureCommonServices(services);
    
    //Services only for staging
    services.Configure();
}

private void ConfigureCommonServices(IServiceCollection services)
{
    //Services common to each environment
}

以防有人也在看这个。在.net core 3+中,这些都已经过时了。更新方式为:

public void Configure(
    IApplicationBuilder app,
    IWebHostEnvironment env,
    ILogger<Startup> logger)
{
    if (env.EnvironmentName == Environments.Development)
    {
        // logger.LogInformation("In Development environment");
    }
}

这可以在没有任何额外属性或方法参数的情况下完成,如下所示:

public void ConfigureServices(IServiceCollection services)
{
    IServiceProvider serviceProvider = services.BuildServiceProvider();
    IHostingEnvironment env = serviceProvider.GetService<IHostingEnvironment>();

    if (env.IsProduction()) DoSomethingDifferentHere();
}