gpt4 book ai didi

c# - .Net Core 为不同的构建配置启动

转载 作者:太空宇宙 更新时间:2023-11-03 22:44:06 25 4
gpt4 key购买 nike

我正在尝试找出一种有效的方法来为不同的构建配置我的 Startup.cs,而无需使用大量讨厌的 IfDef。如果我要配置一个普通的类,我通常只是换出依赖注入(inject)器中的一个组件,一切都会完成,但由于启动类用于配置 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;";

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

最佳答案

这是一个想法。

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();
}
}

然后您可以将公共(public)部分放在某种帮助程序类中,并为每个 Startup 调用您需要的任何部分。每个人的类(class)Startup类。

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

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

An alternative to injecting IHostingEnvironment is to use a conventions-based approach. The app can define separate Startup classes for different environments (for example, StartupDevelopment), and the appropriate startup class is selected at runtime. The class whose name suffix matches the current environment is prioritized. If the app is run in the Development environment and includes both a Startup class and a StartupDevelopment class, the StartupDevelopment class is used.

关于c# - .Net Core 为不同的构建配置启动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50779316/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com