Dependency Injection in .NET MAUI

Dependency injection (DI) is one of the most useful patterns in a growing .NET MAUI application. Instead of creating services directly inside every page, you register them once and let the built-in service container provide the required objects.

🚀 Try dependency injection in the MAUI Playground

Why Use Dependency Injection?

Without DI, a page can become tightly coupled to concrete service implementations. DI makes those dependencies explicit and makes applications easier to test, maintain, and extend.

Register a Service

Service registration normally happens in MauiProgram.cs.

builder.Services.AddSingleton<ISettingsService, SettingsService>();
builder.Services.AddTransient<LoginViewModel>();

Use Singleton for services that should have one instance for the application's lifetime, Transient when a new instance is appropriate each time, and Scoped only when your application's architecture provides a meaningful scope.

Inject a Service into a Page

A MAUI page can receive a registered service through its constructor.

public partial class MainPage : ContentPage
{
    private readonly ISettingsService _settings;

    public MainPage(ISettingsService settings)
    {
        InitializeComponent();
        _settings = settings;
    }
}

Inject Services into View Models

Constructor injection is particularly useful with MVVM because the view model can depend on interfaces rather than concrete implementations.

public class MainViewModel
{
    private readonly ISettingsService _settings;

    public MainViewModel(ISettingsService settings)
    {
        _settings = settings;
    }
}

Choosing a Lifetime

Common DI Mistakes

Conclusion

Dependency injection gives a .NET MAUI application a clean way to manage services and application dependencies. Start with constructor injection and sensible service lifetimes, then introduce interfaces and MVVM as the application grows.

Continue with the .NET MAUI Tutorials roadmap for navigation, MVVM, local storage, APIs, and Blazor Hybrid.

đŸ’Ŧ Comments

Sign in with Google to publish immediately, or comment anonymously and wait for approval.

Comments will appear here when available.