【问题标题】:.Net Core configure start up for different builds.Net Core 为不同的构建配置启动
【发布时间】:2018-11-19 14:48:39
【问题描述】:

我正在尝试找出一种有效的方法来为不同的构建配置我的Startup.cs,而无需使用大量讨厌的 IfDef。如果我要配置一个普通的类,我通常会在 Dependency Injector 中换掉一个组件,一切都会完成,但是由于启动类是用来配置 DI 的,所以这是不可能的。

目前我正在对以下内容进行硬编码:

services.AddAuthentication(options =>
{
     options.DefaultAuthenticateScheme = IdentityServerAuthenticationDefaults.AuthenticationScheme;
     options.DefaultChallengeScheme = IdentityServerAuthenticationDefaults.AuthenticationScheme;
}).AddIdentityServerAuthentication(AuthenticationRule.ConfigureForStaging());
//.AddIdentityServerAuthentication(AuthenticationRule.ConfigureForProduction());

我有一堆语句注释掉了代码库的吞吐量

const string connection = @"Server=StagingServer.com;Database=MyStagingDB;Trusted_Connection=True;";
//const string connection = @"Server=localhost;Database=MyLocalDB;Trusted_Connection=True;";

这不是很有效,而且很容易出错。如何配置我的启动类以轻松切换构建?

【问题讨论】:

  • 您肯定应该使用不同的appSettings.{Environment}.json 文件。当默认情况下从该文件中获取连接字符串时,您对连接字符串进行硬编码这一事实令人担忧。请注意,大多数配置选项都接受 Bind() 调用,该调用直接从 Configuration 变量中获取数据
  • @CamiloTerevinto,谢谢,我会把一些东西移到那里,如果我需要稍微不同的行为应该怎么做?

标签: c# build .net-core


【解决方案1】:

这是一个想法。

public class Program
{
    public static bool IsProduction = false; // shouldn't actually be hard coded.

    public static void Main(string[] args)
    {
        var hostCommon =
            new WebHostBuilder()
                .UseKestrel()
                .UseContentRoot(Directory.GetCurrentDirectory())
                .UseIISIntegration();

        var host =
            IsProduction
                ? hostCommon.UseStartup<StartupProduction>()
                : hostCommon.UseStartup<StartupStaging>();

        host.Build().Run();
    }
}

然后,您可以将公共部分放入某种 Helper 类中,并从每个 Startup 类中调用每个 Startup 类所需的任何部分。

如果您有两个以上的环境,您可以使用 Dictionary&lt;string, Type&gt;Dictionary&lt;string, Func&lt;IWebHostBuilder, IWebHostBuilder&gt;&gt; 并关闭环境名称。

或者,您可以使用 Camilo Terevinto 提到的基于约定的方法。 From Microsoft:

注入 IHostingEnvironment 的另一种方法是使用 基于约定的方法。该应用程序可以定义单独的启动 不同环境的类(例如,StartupDevelopment), 并在运行时选择适当的启动类。班上 其名称后缀与当前环境匹配的优先级。如果 该应用程序在开发环境中运行,并且包括 Startup 类和一个 StartupDevelopment 类,即 StartupDevelopment 使用类。

【讨论】:

  • 如果您有StartupDevelopmentStartupProduction,它是否会根据检测到的环境使用正确的类?请参阅here 了解我的意思。
  • @cwharris,谢谢,这是完美的,我已将配置值移动到应用程序设置,但我的暂存和生产行为略有不同,所以这将有所帮助
  • @cwharris 文档仍然指向 2.1 上完全相同的行为:docs.microsoft.com/en-us/aspnet/core/fundamentals/…。问题是你不需要显式调用UseStartup
  • @CamiloTerevinto 谢谢你的权利,它会根据文档自动解决它if the app is run in the Development environment and includes both a Startup class and a StartupDevelopment class, the StartupDevelopment class is used.
  • 没错,Convention over Configuration 到处都是 :)
猜你喜欢
  • 2012-10-01
  • 2020-02-13
  • 1970-01-01
  • 2017-06-06
  • 1970-01-01
  • 2011-03-16
  • 2010-12-05
  • 2020-07-13
  • 2014-02-05
相关资源
最近更新 更多