Dependency Injection with .NET MAUI Explained! Full Beginner's Guide

James Montemagno · 76K views · 2022 · 19:18

Open on YouTube

Software architecture & designSoftware practice, open source & careerstutorialdated

Why Stack Overflow recommends it

Stack Overflow users link it when answering .NET MAUI questions about constructor injection, registering services in MauiProgram, and resolving services in platform-specific code.

Recommended by 4 people across 4 different months, 2022 to 2023.

What it is

A 19-minute beginner walkthrough by James Montemagno of dependency injection, inversion of control and constructor injection in .NET MAUI, including how Shell resolves dependencies during navigation. It uses a sample app and points to the .NET docs, the CommunityToolkit MVVM source generators and a MAUI workshop.

What people said

Recommends 0wl · 2022-07 · Stack Overflow · on “Dependency injection with JobService subclass in MAUI application”

As per discussion I found on reddit [LINK] it constructor injection is a common issue with Android activities/services etc. but there seems to be a workaround by using dependency resolver the way James Montemagno describes it here [this video] .

Recommends Tyson Swing · 2022-08 · Stack Overflow · on “.NET MAUI Dependency Injection in platform specific code”

I found this on Jame Montemagno's Youtube [LINK] . I think this is what you are looking for. The video is here [this video] . public static class ServiceHelper { public static T GetService<T>() => Current.GetService<T>(); public static IServiceProvider Current => #if WINDOWS10_0_17763_0_OR_GREATER MauiWinUIApplication.Current.Services; #elif ANDROID MauiApplication.Current.Services; #elif IOS || MACCATALYST MauiUIApplicationDelegate.Current.Services; #else null; #endif }

Recommends H.A.H. · 2022-11 · Stack Overflow · on “Why is .NET MAUI Dependency Injection crashing my app?”

This article is not the best source to learn MVVM and DI for MAUI. May I suggest trying CommunityToolkit.MVVM? Check this out: [this video] for example.

Recommends Julian · 2023-05 · Stack Overflow · on “How to handle "Parameterless Constructor" error when I need to pass a ViewModel in C# .Net MAUI?”

In order to use constructor injection with MAUI Shell, you need to register all required dependencies with the MauiAppBuilder instance in your MauiProgram.cs file: var builder = MauiApp.CreateBuilder(); builder .UseMauiApp<App>() .ConfigureFonts(fonts => { fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular"); fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold"); }); builder.Services.AddTransient<IVoterService>(); builder.Services.AddTransient<VotersListPageViewModel>(); builder.Services.AddTransient<VotersListPageView>(); You don't need to handle any of the dependency injection yourself like this, the constructor arguments are passed down by Shell automatically. Note : You'll have