亲宝软件园·资讯

展开

启动类选择

尾牙衣子 人气:0

AspNet Core 多环境的配置方式有一种基于Startup类的选择。

  1. webBuilder.UseStartup() //显式注册、会靶定Startup.cs
  2. webBuilder.UseStartup(Assembly.GetExecutingAssembly().FullName); //多环境写法,根据环境变量选择基于约定名的类

还有其它两种方式这里不细说,配置多环境很明显不是采用显式注册。因此以下测试均采用方式二

尝试一:不同环境的优先级

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        IConfigurationRoot root = new ConfigurationBuilder().AddJsonFile("appsettings.Production.json").Build();
    }
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
    }
}
默认
public class StartupProduction
{
    public void ConfigureServices(IServiceCollection services)
    {
        IConfigurationRoot root = new ConfigurationBuilder().AddJsonFile("appsettings.Production.json").Build();
    }
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
    }
}
Production环境

结论:很明显是环境变量优先

尝试二:不同命名空间下的优先级

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        IConfigurationRoot root = new ConfigurationBuilder().AddJsonFile("appsettings.Production.json").Build();
    }
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
    }
}
无命名空间
namespace Other
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            IConfigurationRoot root = new ConfigurationBuilder().AddJsonFile("appsettings.Production.json").Build();
        }
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
        }
    }
}
任意命名空间
namespace AspnetCore
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            IConfigurationRoot root = new ConfigurationBuilder().AddJsonFile("appsettings.Production.json").Build();
        }
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
        }
    }
}
当前命名空间

结论:无命名空间优先在情理之中,可任意命名空间竟然比当前的优先集要高,有些出人意料

后续

其一:多环境配置方式往小的说,还可以有基于配置文件的选择传送门,和基于配置方法的选择两种配置方式

其二:其它两种方式分别是

  1. webBuilder.Configure(app => {}) //注册一个DelegateStartup对象
  2. webBuilder.UseSetting("StartupAssembly", Assembly.GetEntryAssembly().FullName) //直接指定法

加载全部内容

相关教程
猜你喜欢
用户评论