Creating Dynamic Tab Bars and Environment Deployments in .NET MAUI

Dynamic tabbar For different Environment Deployment (Dev,Prod, staginG)


In this blog post, we will explore how to create dynamic tab bars in a .NET MAUI application and manage different deployment environments (Development, Staging, Production) using configuration files.

 A special thank you to Gowtham Nagiri for inspiring this topic! Your insights have helped shape this exploration, and I appreciate your contribution to the .NET MAUI community.

This approach allows your application to adapt to different environments without changing the codebase. Let's dive into the details!

Understanding the Dynamic Tab Bars

Dynamic tab bars enable you to display different tabs based on the application's current environment or other configurations. For example, in a Development environment, you might want to show additional features or diagnostic tabs that aren’t present in Production. This feature is particularly useful in mobile applications, where the user experience can be customized based on the environment in which the application is running.

Step 1: Create Environment-Specific Configuration Files

To handle different settings for each environment, we will create separate configuration files. These files will contain environment-specific settings like API URLs and feature flags. Using separate configuration files allows you to change the application's behavior based on the environment without altering the code.



Configuration Files

We'll create three JSON files for our configurations:

  • appsettings.json: This will contain the default settings.
  • appsettings.Staging.json: This will include settings specific to the Staging environment.
  • appsettings.Development.json: This will include settings specific to the Development environment.

appsettings.json


// appsettings.json
{
    "ApiBaseUrl": "https://api.example.com",
    "FeatureFlag": false  // Only stable features for Production
}
    

appsettings.Staging.json


// appsettings.Staging.json
{
    "ApiBaseUrl": "https://api.staging.example.com",
    "FeatureFlag": true  // Enable features for Staging
}
    

appsettings.Development.json


// appsettings.Development.json
{
    "ApiBaseUrl": "https://api.dev.example.com",
    "FeatureFlag": true  // Enable features for Development
}
    


Step 2: Load Configuration in .NET MAUI

Now that we have our configuration files, we need to load them based on the environment variable set. This is done in the MauiProgram.cs file, where we define how the application should behave based on the environment.

Setting Up the Environment

We will use the Environment.SetEnvironmentVariable method to define which environment the application is currently running in. The following code snippet shows how to retrieve the current environment setting and load the appropriate configuration file:


using Microsoft.Extensions.Configuration;

public static class MauiProgram
{
    public static MauiApp CreateMauiApp()
    {
        var builder = MauiApp.CreateBuilder();

        // Set the current environment to Development
        Environment.SetEnvironmentVariable("DOTNET_MAUI_ENV", DeployEnvironmentEnum.Development.ToString());
        var environment = Environment.GetEnvironmentVariable("DOTNET_MAUI_ENV") ?? "Production";

        // Build the configuration
        var config = new ConfigurationBuilder()
            .SetBasePath(AppContext.BaseDirectory)
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
            .AddJsonFile($"appsettings.{environment}.json", optional: true, reloadOnChange: true)
            .Build();

        // Retrieve settings
        string apiBaseUrl = config["ApiBaseUrl"];
        bool featureFlag = bool.Parse(config["FeatureFlag"]);

        // Register AppSettings as a singleton
        builder.Services.AddSingleton(new AppSettings(apiBaseUrl, featureFlag));

        // Set up the main application with injected AppSettings
        builder.UseMauiApp<App>();

        return builder.Build();
    }
}
    


In this setup:

  • We first set the environment variable DOTNET_MAUI_ENV to define the current environment.
  • We then build our configuration using the ConfigurationBuilder class to include the appropriate settings based on the environment variable.
  • Finally, we register AppSettings as a singleton in the application's service container, allowing us to use the settings throughout the application.

Step 3: Create the DynamicTabbedPage

Next, we create the DynamicTabbedPage where we can dynamically add tabs based on the current environment:

Defining the DynamicTabbedPage

The DynamicTabbedPage class will inherit from TabbedPage and will use the settings defined in AppSettings to determine which tabs to display:


using Microsoft.Extensions.DependencyInjection;

public enum DeployEnvironmentEnum
{
    Production,
    Staging,
    Development 
}

public class DynamicTabbedPage : TabbedPage
{
    private readonly AppSettings _appSettings;

    public DynamicTabbedPage()
    {
        _appSettings = App.AppSettings; // Retrieve the singleton AppSettings instance
        CreateDynamicTabs(); // Call the method to create tabs
    }

    private void CreateDynamicTabs()
    {
        var environment = Environment.GetEnvironmentVariable("DOTNET_MAUI_ENV"); // Get the current environment
        
        // Add common tabs
        Children.Add(new ContentPage { Title = "Home" });
        Children.Add(new ContentPage { Title = "Settings" });

        // Add environment-specific tabs
        if (_appSettings.FeatureFlag)  // Check the feature flag for additional features
        {
            Children.Add(new ContentPage { Title = "Beta" }); // Beta tab for testing new features
        }

        // Adding environment-specific tabs based on the current environment
        if (environment == DeployEnvironmentEnum.Development.ToString())
            Children.Add(new ContentPage { Title = "Development" });
        if (environment == DeployEnvironmentEnum.Staging.ToString())
            Children.Add(new ContentPage { Title = "Staging" });
        if (environment == DeployEnvironmentEnum.Production.ToString())
            Children.Add(new ContentPage { Title = "Production" });
    }
}
    


In this class:

  • The DynamicTabbedPage constructor retrieves the AppSettings singleton instance to access the current settings.
  • The CreateDynamicTabs method builds the tab structure based on the environment and feature flags.
  • Common tabs are added for all environments, while additional tabs are conditionally included based on the current environment and the feature flag.

Step 4: Using AppSettings in App.xaml.cs

Next, we will set the DynamicTabbedPage as the main page in the App.xaml.cs file:


public partial class App : Application
{
    public static AppSettings AppSettings { get; private set; } // Static property for AppSettings
    
    public App(AppSettings appSettings)
    {
        InitializeComponent(); // Initialize the application
        AppSettings = appSettings; // Store the AppSettings

        // Set MainPage to DynamicTabbedPage
        MainPage = new DynamicTabbedPage();
    }
}
    

In the App class:

  • We define a static property AppSettings to store the settings that can be accessed throughout the application.
  • In the constructor, we initialize the application and set the MainPage to be an instance of DynamicTabbedPage.

Conclusion

By following these steps, you can create a .NET MAUI application with dynamic tab bars that change based on the deployment environment. This approach allows for flexibility and improved maintainability across different configurations. Using configuration files helps ensure that sensitive or environment-specific information is not hard-coded into your application, promoting best practices in software development.

Next Steps

Consider implementing logging for each environment and using feature flags effectively to manage your application's functionality. This will help you maintain a clean and efficient codebase while adapting to the needs of different deployment environments. Additionally, explore how to manage user authentication or other services that may differ across environments.

Additional Resources

If you want to dive deeper into .NET MAUI or learn about best practices in application development, consider checking the official documentation, community forums, or online courses tailored to .NET MAUI.

Comments

Popular posts from this blog

Push Notifications in .NET MAUI: A Comprehensive Guide

Explore the UI libraries available for .NET MAUI at no cost.

Push Notification using Firebase in xamarin form (Android and IOS)