.NET MAUI环境变量

4

如何在.NET MAUI中查找当前环境是否为development?在我的Blazor WASM中,我只需执行以下操作:

builder.HostEnvironment.IsDevelopment()

但是在MauiAppBuilder中,我没有看到任何环境属性。

3个回答

2

对于这个问题,我通常使用if指令来解决。

例如,如果我想要在发布版本和调试版本中为变量设置不同的值,我会像下面这样做:

#if DEBUG
var a = "debug";
#elif RELEASE
var a = "release"
#endif

祝你好运,希望这有所帮助


0

目前我找到的唯一有效方法是手动设置变量。在Windows中,我设置了一个用户环境变量 ASPNETCORE_ENVIRONMENT=Development,然后通过以下方式访问它:

var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");


1
为了让你不必手动操作,你可以使用Environment.SetEnvironmentVariable("name", "value"); - undefined

0
我采用了一种稍微不同的方法。我创建了MobileHostEnvironment
internal sealed class MobileHostEnvironment : IHostEnvironment
{
    public string EnvironmentName { get; set; } = Environments.Development;
    public string ApplicationName { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
    public string ContentRootPath { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
    public IFileProvider ContentRootFileProvider { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
}

然后在MauiProgram.cs的开头,我声明并初始化它,如下所示:
private static readonly MobileHostEnvironment _mobileHostEnvironment = new()
{
    EnvironmentName = Environments.Production
};

在服务注册之前,我引用了using Microsoft.Extensions.Hosting;
#if DEBUG
        _mobileHostEnvironment.EnvironmentName = Environments.Development;
#endif

这样,调试中的应用程序始终是开发环境,发布的应用程序始终是生产环境。

当然,您可以通过将其注册到依赖容器中来改进此流程。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接