Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET MAUI Environment variable

Is there a way how to find out that the current environment in .NET MAUI is development ? Because before in my Blazor WASM I did just: builder.HostEnvironment.IsDevelopment()

But in MauiAppBuilder I dont see any environment property.

like image 810
ssamko Avatar asked Aug 05 '26 20:08

ssamko


2 Answers

I approached it a little bit different. I have created 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(); }
}

then at the beginning of MauiProgram.cs I declare and initialize it like:

private static readonly MobileHostEnvironment _mobileHostEnvironment = new()
{
    EnvironmentName = Environments.Production
};

with a reference to using Microsoft.Extensions.Hosting; and before service registering I have:

#if DEBUG
        _mobileHostEnvironment.EnvironmentName = Environments.Development;
#endif

So that way app in debug is always Development and released one is always Production.

Ofc you can improve this flow by registering it into dependency container.

like image 63
ssamko Avatar answered Aug 07 '26 19:08

ssamko


What I usually do for this is I use the "if" directive.

For instance, if I want to set a different value to var in release than in debug I would do something like below:

#if DEBUG
var a = "debug";
#elif RELEASE
var a = "release"
#endif
like image 25
FreakyAli Avatar answered Aug 07 '26 18:08

FreakyAli



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!