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
- Singleton: useful for application-wide state and reusable services.
- Transient: useful for lightweight objects where each request should receive a new instance.
- Scoped: use carefully and understand the scope created by the hosting architecture.
Common DI Mistakes
- Forgetting to register a service before injecting it.
- Registering state as transient when it must survive across pages.
- Putting too much global mutable state into singletons.
- Depending on concrete classes everywhere instead of useful interfaces.
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.