.NET MAUI App Architecture

Understanding the architecture of a .NET Multi-platform App UI (MAUI) application is fundamental to building scalable, maintainable, and high-performing cross-platform applications. MAUI applications are built with a clear separation of concerns, leveraging patterns like MVVM (Model-View-ViewModel) to enhance testability and code organization.

Core Components

A MAUI application consists of several key components that work together to deliver a seamless user experience across different platforms.

1. The Application Class

Every MAUI application has a single entry point, typically named MauiProgram.cs. This class is responsible for bootstrapping the application and configuring its services. The CreateMauiApp() method is the core of the entry point.


using Microsoft.Maui.Hosting;

namespace MyMauiApp
{
    public static class MauiProgram
    {
        public static MauiApp CreateMauiApp()
        {
            var builder = MauiApp.CreateBuilder();
            builder
                .UseMauiApp()
                .ConfigureFonts(fonts =>
                {
                    fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
                });

            // Register services here
            // builder.Services.AddSingleton();

            return builder.Build();
        }
    }
}
            

2. The Application Lifecycle

The App.xaml and App.xaml.cs files define the application's core class, which inherits from Microsoft.Maui.Controls.Application. This class is the root of your application's visual tree and manages the application's lifecycle events such as startup, sleep, and resume.

The App.xaml.cs file typically contains the logic for setting the application's main page:


namespace MyMauiApp
{
    public partial class App : Application
    {
        public App()
        {
            InitializeComponent();

            // Set the main page of the application
            MainPage = new NavigationPage(new Views.HomePage());
        }
    }
}
            

3. Pages

Pages represent the distinct screens or views within your application. MAUI provides various page types such as ContentPage, FlyoutPage, TabbedPage, and NavigationPage. Each page typically has an associated XAML file for defining its UI structure and a C# code-behind file for handling its logic.

MAUI App Architecture Diagram

A simplified representation of MAUI app structure.

4. Views (XAML)

The User Interface (UI) of a MAUI application is predominantly defined using XAML (Extensible Application Markup Language). XAML allows for a declarative way to define the layout and appearance of your application's elements. These elements are often data-bound to properties in the ViewModel.

Example of a ContentPage in XAML:


<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:viewmodels="clr-namespace:MyMauiApp.ViewModels"
             x:Class="MyMauiApp.Views.HomePage">

    <ContentPage.BindingContext>
        <viewmodels:HomeViewModel />
    </ContentPage.BindingContext>

    <VerticalStackLayout Padding="20" Spacing="15"
                     HorizontalOptions="Center" VerticalOptions="Center">
        <Label Text="{Binding WelcomeMessage}"
               FontSize="Large"
               HorizontalOptions="Center" />
        <Button Text="Click Me" Command="{Binding ClickCommand}"
                HorizontalOptions="Center" />
    </VerticalStackLayout>

</ContentPage>
            

5. ViewModels (C#)

ViewModels serve as intermediaries between the View (XAML) and the Model (data and business logic). They expose data to the View through properties and handle user interactions via commands. The MVVM pattern promotes loose coupling and makes applications easier to test.


using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using System.Windows.Input;

namespace MyMauiApp.ViewModels
{
    public partial class HomeViewModel : ObservableObject
    {
        [ObservableProperty]
        string welcomeMessage = "Welcome to MAUI!";

        public ICommand ClickCommand { get; }

        public HomeViewModel()
        {
            ClickCommand = new RelayCommand(PerformClick);
        }

        private void PerformClick()
        {
            WelcomeMessage = "Button Clicked!";
        }
    }
}
            

6. Models

Models represent the application's data and business logic. They are plain C# objects that encapsulate the data structures and operations relevant to the application's domain.


namespace MyMauiApp.Models
{
    public class User
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }
}
            

Platform Abstraction

.NET MAUI provides a rich set of APIs that abstract the underlying platform-specific UI elements and functionalities. This abstraction allows developers to write a single codebase that runs on iOS, Android, macOS, and Windows.

Key Concepts

  • Controls: MAUI provides a unified set of controls that map to native controls on each platform.
  • Layouts: Flexible layout containers like VerticalStackLayout, HorizontalStackLayout, Grid, and FlexLayout ensure responsive UI design.
  • Platform-Specific APIs: For scenarios requiring direct access to platform features, MAUI offers mechanisms to invoke platform-specific code.

Dependency Injection

MAUI has built-in support for dependency injection, making it easy to manage and inject services throughout your application. You can register services in MauiProgram.cs.


// In MauiProgram.cs
builder.Services.AddSingleton<IMessagingService, MessagingService>();
            

And then inject them into your ViewModels or other services:


public partial class SomeViewModel : ObservableObject
{
    private readonly IMessagingService _messagingService;

    public SomeViewModel(IMessagingService messagingService)
    {
        _messagingService = messagingService;
    }

    // Use _messagingService here
}
            

Best Practice

Embrace the MVVM pattern for building MAUI applications. This practice significantly improves code maintainability, testability, and the overall development experience.

By understanding these architectural concepts, you can effectively build robust and cross-platform applications with .NET MAUI.