What problem does it solve?
MAUI apps often struggle with inconsistent service lifetimes, poor testability, and scattered registrations. This guide provides a clear, end-to-end approach to dependency injection in MAUI, covering service registration, lifetime choices, constructor injection, automatic resolution via Shell navigation, explicit resolution, platform-specific registrations, and test-friendly patterns.
Core Features & Use Cases
- Service registration in MauiProgram.cs: register services, viewmodels, and pages with appropriate lifetimes.
- Lifetime guidance: AddSingleton, AddTransient, and AddScoped usage with examples.
- Constructor Injection: prefer DI through constructors for testable, decoupled code.
- Automatic resolution via Shell Navigation: DI resolves registered pages and viewmodels via Shell routes.
- Explicit Resolution: resolve services on-demand via IServiceProvider when needed.
- Platform-Specific Service Registration: select implementations per platform with preprocessor directives.
- Testability & Interface-First Pattern: define interfaces to enable mocks in tests; swap implementations without changing production code.
- Gotchas & Best Practices: note DI timing with XAML resources and late-bound resolution in App.CreateWindow.
Quick Start
Register your services in MauiProgram.cs and wire ViewModels to Pages.