Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 42 ยท MVVM and Navigation

Dependency Injection and View Models

Use dependency injection in .NET MAUI: register services, view models and pages in MauiProgram, choose singleton, transient or scoped lifetimes, inject into constructors, and test with fakes.

A view model rarely works alone. It needs a repository to load products, a service to talk to a web API, a way to show an alert. If every view model creates these with new, the classes become glued together: you cannot test them without a real network and you cannot swap a real service for a fake. Dependency injection (DI) solves this: a class declares what it needs in its constructor, and a container supplies those objects.

MAUI's own container cannot run on this site, but it is the standard Microsoft.Extensions.DependencyInjection container used in ASP.NET Core, and that library works on our runner. The runnable blocks are therefore real DI code; only the MAUI wiring (MauiProgram, Shell) is read-only.

The idea in four lines

C#
public interface IProductService
{
    Task<IReadOnlyList<Product>> GetProductsAsync();
}

public class ProductsViewModel(IProductService service) : ObservableObject
{
    // the view model asks for an IProductService; it never calls "new HttpProductService()"
}

The view model depends on an interface (an abstraction). At run time the container passes in the real HttpProductService; in a test you pass in a FakeProductService that returns fixed data. This is also called inversion of control.

Registering services in MauiProgram

MAUI creates a container for you and exposes it as builder.Services in MauiProgram.CreateMauiApp (see App Lifecycle and MauiProgram). You register things before Build():

C#
public static MauiApp CreateMauiApp()
{
    var builder = MauiApp.CreateBuilder();
    builder.UseMauiApp<App>();

    // services
    builder.Services.AddSingleton<IProductService, HttpProductService>();
    builder.Services.AddSingleton<ISettingsStore, PreferencesSettingsStore>();
    builder.Services.AddTransient<HttpClient>();            // or use AddHttpClient

    // view models and pages
    builder.Services.AddTransient<ProductsViewModel>();
    builder.Services.AddTransient<ProductsPage>();
    builder.Services.AddTransient<ProductDetailViewModel>();
    builder.Services.AddTransient<ProductDetailPage>();

    return builder.Build();
}

Lifetimes

Lifetime One instance per... Use for
AddSingleton the whole app caches, settings, HTTP clients, services holding shared state
AddTransient every request for it pages and view models that should start fresh
AddScoped scope rarely used in MAUI, since there is no per-request scope unless you create one

A page that is a singleton keeps its old state when you navigate back to it, which is sometimes wanted (a tab's main page) and often surprising. A common rule is: services are singletons, pages and their view models are transient, except for pages that live for the app's whole life.

A trap is a captive dependency: a singleton that depends on a transient one keeps that single instance forever. Never inject a view model into a singleton service.

C# Run the real DI container: lifetimes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Constructor injection into pages and view models

MAUI resolves pages from the container when Shell creates them (see Shell Navigation) or when you ask for them with a service provider. A page asks for its view model; the view model asks for services:

C#
public partial class ProductsPage : ContentPage
{
    public ProductsPage(ProductsViewModel viewModel)
    {
        InitializeComponent();
        BindingContext = viewModel;
    }
}

The container builds the whole graph for you: ProductsPage needs ProductsViewModel, which needs IProductService, which needs HttpClient. If a registration is missing you get an InvalidOperationException that names the missing type the first time the page is created, so test every page once.

Put x:DataType="vm:ProductsViewModel" on the page so the bindings are checked while compiling, as explained in Data Binding Basics.

Pages created by DataTemplate in XAML

A page created in XAML (<ContentPage ...> inside a ShellContent with ContentTemplate="{DataTemplate local:MainPage}") is resolved through the container, so constructor injection works there too. A page created with new MainPage() is not injected, which is the most common reason for a constructor that suddenly has no parameters available.

Interfaces for platform services

DI also hides platform APIs. MAUI offers interfaces such as IConnectivity, IGeolocation, IFileSystem, IPreferences, ISecureStorage and IDeviceInfo; their static counterparts (Connectivity.Current, Preferences.Default) are shortcuts. Registering and injecting the interfaces makes view models testable:

C#
builder.Services.AddSingleton(Connectivity.Current);
builder.Services.AddSingleton(Preferences.Default);
builder.Services.AddSingleton(FileSystem.Current);

public class SyncViewModel(IConnectivity connectivity, IPreferences prefs)
{
    public bool CanSync => connectivity.NetworkAccess == NetworkAccess.Internet;
}

In a unit test you pass a fake IConnectivity that says "offline" and check that CanSync is false.

Testing with fakes

Because the view model depends on an interface, a test needs no network. The following program plays the role of a test: it creates the view model with a fake service that fails, and checks that the error message is shown.

C# Test a view model with a fake service

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

HttpClient and options

Create HttpClient through the container too, so a base address and timeout are in one place:

C#
builder.Services.AddHttpClient<IProductService, HttpProductService>(client =>
{
    client.BaseAddress = new Uri("https://api.example.com/");
    client.Timeout = TimeSpan.FromSeconds(15);
});

AddHttpClient needs the Microsoft.Extensions.Http package. The REST lesson uses it. Configuration values can come from an embedded appsettings.json; load it with ConfigurationBuilder and register IConfiguration as a singleton.

Common mistakes

  • Resolving services with ServiceHelper.GetService<T>() (a service locator) everywhere. Constructor injection is clearer and testable.
  • Forgetting to register a page or view model: the crash appears at navigation time.
  • Making view models singletons, so a "new" screen shows the previous user's data.
  • Capturing a transient in a singleton (captive dependency).
  • Creating pages with new and wondering why injection does not work.

DI in a MAUI app

Register builder.Services in MauiProgram
Inject Constructor parameters
Lifetime Singleton, transient, scoped
Fake it Swap an interface in tests

Pages and view models transient, shared services singleton.

1 / 2

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where do you register services in a MAUI app?

    MauiProgram exposes the container's ServiceCollection as builder.Services; registrations must happen before Build().
  2. 2. A page is registered with AddTransient. What happens when you navigate to it twice?

    Transient means a new instance for each request for the type.
  3. 3. Why depend on IProductService instead of HttpProductService?

    An abstraction decouples the view model from a specific implementation.
  4. 4. What is a captive dependency?

    A longer-lived object that receives a shorter-lived one keeps that one alive, so it never behaves as transient.

Summary

  • Constructor injection with interfaces keeps view models decoupled and testable.
  • Register services, view models and pages on builder.Services in MauiProgram.
  • Services are usually singletons; pages and view models are transient.
  • Pages created through Shell or DataTemplate are resolved by the container; new Page() bypasses it.
  • Inject platform interfaces (IConnectivity, IPreferences) and use fakes in tests.

Next: Shell Navigation