.NET MAUI Dependency Injection: Register and Use Services
.NET MAUI includes the .NET dependency injection container, making it straightforward to register application services and inject them into pages, view models, and other components.
đ Try the interactive DI example in the MAUI Playground
Register a Service
builder.Services.AddSingleton<ISettingsService, SettingsService>();
builder.Services.AddTransient<MainViewModel>();
Use singleton lifetime for genuinely shared state or stateless services that can safely be shared. Use transient or scoped patterns according to the lifetime needs of the application.
Inject Into a Page
public partial class MainPage : ContentPage
{
private readonly ISettingsService settings;
public MainPage(ISettingsService settings)
{
InitializeComponent();
this.settings = settings;
}
}
Constructor Injection Is Preferred
Constructor injection makes dependencies explicit and allows the container to validate the object graph when resolving the page.
Register Pages Too
If a page has constructor dependencies, register the page or ensure the navigation mechanism resolves it through the service provider.
Keep Platform Code Isolated
Services that depend on Android, iOS, Windows, or MacCatalyst APIs can be hidden behind interfaces. This keeps shared application logic easier to test and maintain.
Common Mistakes
- Creating service instances manually with
neweverywhere. - Using singleton lifetime for mutable per-user state without considering concurrency.
- Registering an interface but requesting a different implementation type.
- Putting too much application state into one global singleton.
Conclusion
Dependency injection is one of the simplest ways to keep a MAUI application modular. Register services centrally, inject dependencies through constructors, and choose lifetimes based on ownership and state requirements.
Ask AlgoLassi and get an answer plus the tutorials worth studying next.
đŦ Comments
Sign in with Google to publish immediately, or comment anonymously and wait for approval.
Comments will appear here when available.