Using MAUI Dependency Injection and Tips


Using MAUI Dependency Injection and Tips

.NET MAUI (Multi-platform App UI) is a cross-platform framework used for developing modern mobile and desktop applications. One of the standout features of MAUI is its built-in support for Dependency Injection infrastructure. MAUI Dependency Injection makes your code more modular, testable, and maintainable. In this article, you will learn step by step how to use Dependency Injection in MAUI applications and discover practical tips to keep in mind.

The Logic of Dependency Injection in MAUI

In MAUI projects, Microsoft.Extensions.DependencyInjection is used in the background to resolve dependencies. When starting the project, you can begin by adding your services in the MauiProgram.cs file's CreateMauiApp method:

public static MauiApp CreateMauiApp()
{
    var builder = MauiApp.CreateBuilder();
    builder
        .UseMauiApp<App>()
        .ConfigureFonts(fonts => {
            fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
        });
    
    // Add services
    builder.Services.AddSingleton<IMyService, MyService>();
    
    return builder.Build();
}

In the example above, the IMyService interface and its corresponding MyService implementation have been added to the DI container. Now you can use this service directly with dependency injection in any page or ViewModel you need:

public class MainPageViewModel
{
    private readonly IMyService _myService;
    public MainPageViewModel(IMyService myService)
    {
        _myService = myService;
    }
}

Things to Consider When Using MAUI Dependency Injection

Registration Types: Singleton, Transient, Scoped

With Singleton, only one instance of a service is used from the start to the end of the application. Transient creates a new object upon each request. In MAUI applications, the Scoped registration is not recommended by default; usually, Singleton and Transient are preferred.

// Singleton usage example
builder.Services.AddSingleton<IMyService, MyService>();
// Transient usage example
builder.Services.AddTransient<IOtherService, OtherService>();

ViewModel and Page Navigation

In MAUI, by injecting pages and ViewModels via dependency injection, you can provide flexibility in navigation processes. For example, to bind a ViewModel to a page with DI:

builder.Services.AddTransient<MainPageViewModel>();
builder.Services.AddTransient<MainPage>();

This approach also facilitates adding mock services during test writing.

Result: What MAUI Dependency Injection Provides

With MAUI Dependency Injection, managing dependencies becomes quite easy even in large and complex applications. This structure increases your code's readability, sustainability, and testability. With the right configuration and scope selections, you can comfortably apply modern software development practices using Dependency Injection in MAUI applications.