簡體   English   中英

在自托管的.net core 2.2應用程序上正確使用IsDevelopement()

[英]Proper use of IsDevelopement() on self hosted .net core 2.2 application

我有一個自托管的.NET Core 2.2控制台應用程序,該應用程序不使用Web主機構建器,因為我不需要此服務的HTTP端點。

我正在嘗試通過托管環境的IsDevelopment()方法來利用環境變量,但是它總是以Production形式返回。

以下是我設置主機構建器的方式。 我有一個名為ASPNETCORE_ENVIRONMENT的環境變量,其值為Development ,這使我提出兩個問題。

  1. 在構建自己的主機時進行設置的正確方法是什么,以便在構建主機時可以有條件地向配置中添加用戶密碼?
  2. 第二個問題是,因為我的應用程序不是ASP.NET核心應用程序,是否可以使用ASPNETCORE_ENVIRONMENT以外的其他環境變量?

我意識到我可能可以在構建HostBuilder之前編寫代碼,該HostBuilder明確尋找環境變量並手動設置環境,但是ASP.NET Core似乎將其隱藏在幕后,所以我想看看是否有一種獲取方法當我不使用Web Host Builder時,會發生類似的行為。

private static IHost BuildEngineHost(string[] args)
{
    var engineBuilder = new HostBuilder()
        .ConfigureAppConfiguration((hostContext, config) =>
        {
            config.SetBasePath(Directory.GetCurrentDirectory());
            config.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
            config.AddEnvironmentVariables();
            if(hostContext.HostingEnvironment.IsDevelopment())
                config.AddUserSecrets<EngineOptions>();
        })
        .ConfigureServices((hostContext, services) =>
        {
            services.Configure<EngineOptions>(hostContext.Configuration.GetSection("EngineOptions"));
            services.AddHostedService<EtlEngineService>();
        })
        .ConfigureLogging((hostContext, logging) =>
        {
            logging.AddConfiguration(hostContext.Configuration.GetSection("Logging"));
            logging.AddConsole();
        });
    return engineBuilder.Build();
}

更新:在配置應用程序之前,需要以下配置主機

.ConfigureHostConfiguration(config =>
{
    config.AddCommandLine(args);
    config.AddEnvironmentVariables();
})

這是在.ConfigureAppConfiguration()之前調用的,並且是從任何稱為“環境”的變量加載的,這意味着我不必使用ASPNET_ENVIRONMENT。

https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/host/generic-host?view=aspnetcore-2.2

在構建自己的主機時進行設置的正確方法是什么,以便在構建主機時可以有條件地向配置中添加用戶密碼?

正確的方法是不要在BuildEngineHost方法中擁有當前擁有的所有代碼行。 如果您使用的是ASP.Net Core 2.2,則已經為您設置了編寫的那些設置。 在您的Program.cs文件中,您應該僅具有以下內容:

public class Program
{
    public static void Main(string[] args)
    {
        CreateWebHostBuilder(args).Build().Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>();
}

當您查看GitHub上的 CreateDefaultBuilder方法實現時,默認情況下您將嘗試執行的操作已經完成。 這是CreateDefaultBuilder的實現:

public static IWebHostBuilder CreateDefaultBuilder(string[] args)
{
    var builder = new WebHostBuilder();

    if (string.IsNullOrEmpty(builder.GetSetting(WebHostDefaults.ContentRootKey)))
    {
        builder.UseContentRoot(Directory.GetCurrentDirectory());
    }
    if (args != null)
    {
        builder.UseConfiguration(new ConfigurationBuilder().AddCommandLine(args).Build());
    }

    builder.ConfigureAppConfiguration((hostingContext, config) =>
    {
        var env = hostingContext.HostingEnvironment;

        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, logging) =>
    {
        logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
        logging.AddConsole();
        logging.AddDebug();
        logging.AddEventSourceLogger();
    }).
    UseDefaultServiceProvider((context, options) =>
    {
        options.ValidateScopes = context.HostingEnvironment.IsDevelopment();
    });

    ConfigureWebDefaults(builder);

    return builder;
}

無論如何,如果您不想使用此實現,因此要回答第二個問題,則需要使用以下行:

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

在此行之后:

config.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);

env變量是一種IHostingEnvironment類型,需要注入到BuildEngineHost方法中。

我可以通過在AppConfiguration之前調用ConfigureHostConfiguration()初始化具有正確值的托管環境,從而在我從以下Microsoft文檔中找到的主機中正確設置環境值。

https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/host/generic-host?view=aspnetcore-2.2

private static IHost BuildEngineHost(string[] args)
{
    var engineBuilder = new HostBuilder()
        .ConfigureHostConfiguration(config =>
        {
            config.AddEnvironmentVariables();
            config.AddCommandLine(args);
        })
        .ConfigureAppConfiguration((hostContext, config) =>
        {
            config.SetBasePath(Directory.GetCurrentDirectory());
            config.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
            config.AddEnvironmentVariables();
            if(hostContext.HostingEnvironment.IsDevelopment())
                config.AddUserSecrets<EngineOptions>();
        })
        .ConfigureServices((hostContext, services) =>
        {
            services.Configure<EngineOptions>(hostContext.Configuration.GetSection("EngineOptions"));
            services.AddHostedService<EtlEngineService>();
        })
        .ConfigureLogging((hostContext, logging) =>
        {
            logging.AddConfiguration(hostContext.Configuration.GetSection("Logging"));
            logging.AddConsole();
        });
    return engineBuilder.Build();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM