asp.net-core 配置多个环境

示例

本示例说明如何在一个Startup类中使用不同的依赖注入配置和单独的中间件配置多个环境。

除了中和方法可以使用,并有环境相关的配置。public void Configure(IApplicationBuilder app)public void ConfigureServices(IServiceCollection services)Configure{EnvironmentName}Configure{EnvironmentName}Services

使用这种模式可以避免if/else在一个方法/Startup类中增加太多逻辑,并保持其清洁和分离。

public class Startup
{
    public void ConfigureServices(IServiceCollection services) { }
    public void ConfigureStaggingServices(IServiceCollection services) { }
    public void ConfigureProductionServices(IServiceCollection services) { }
    
    public void Configure(IApplicationBuilder app) { }
    public void ConfigureStagging(IApplicationBuilder app) { }
    public void ConfigureProduction(IApplicationBuilder app) { }
}

当找不到Configure{Environmentname}或时Configure{Environmentname}Services,它将分别回落到Configure或ConfigureServices。

相同的语义也适用于Startup该类。StartupProduction将在ASPNETCORE_ENVIRONMENT变量设置为时使用,并在变量为或时Production回退StartupStaggingDevelopment

一个完整的例子:

public class Startup
{
    public Startup(IHostingEnvironment hostEnv)
    {
        // 设置配置源。
        var builder = new ConfigurationBuilder()
            .SetBasePath(hostEnv.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
            .AddJsonFile($"appsettings.{hostEnv.EnvironmentName}.json", optional: true, reloadOnChange: true);

        if (hostEnv.IsDevelopment())
        {
            // 这将使遥测数据更快地通过Application Insights管道推送,从而使您可以立即查看结果。
            builder.AddApplicationInsightsSettings(developerMode: true);
        }

        builder.AddEnvironmentVariables();
        Configuration = builder.Build();
    }

    public IConfigurationRoot Configuration { get; set; }

    //运行时将调用此方法。使用此方法向容器添加服务
    public static void RegisterCommonServices(IServiceCollection services) 
    {
        services.AddScoped<ICommonService, CommonService>();
        services.AddScoped<ICommonRepository, CommonRepository>();
    }
    
    public void ConfigureServices(IServiceCollection services)
    {
        RegisterCommonServices(services);
        
        services.AddOptions();
        services.AddMvc();
    }

    public void ConfigureDevelopment(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        app.UseBrowserLink();
        app.UseDeveloperExceptionPage();

        app.UseApplicationInsightsRequestTelemetry();
        app.UseApplicationInsightsExceptionTelemetry();
        app.UseStaticFiles();
        app.UseMvc();
    }

    // 此配置中没有控制台记录器和调试工具
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddDebug();

        app.UseApplicationInsightsRequestTelemetry();
        app.UseApplicationInsightsExceptionTelemetry();
        app.UseStaticFiles();
        app.UseMvc();
    }
}