TL;DR: Boost Your .NET MAUI Development with Dependency Injection! Effortlessly write cleaner, more manageable .NET MAUI apps by leveraging dependency injection. This powerful technique promotes loosely coupled classes, reusable code, and simplified testing – all essential ingredients for robust cross-platform development. Dive deeper and unlock the full potential of dependency injection in your .NET MAUI projects.
As you know, .NET MAUI evolved from Xamarin.Forms with a better developer experience and better performance. Like adding a gem to a crown, .NET MAUI allows the use of dependency injection way easier than Xamarin.Forms.
In this blog, we’ll see how easy it is to use dependency injection in a .NET MAUI application.
What is dependency injection?
Dependency injection is just a way that an object (client) receives other objects (services) that it depends on. Here, injector means the method or code that passes the service object to the client object. Dependency injection is a version of the inversion of control pattern. Here, the service class will inject dependencies into an object at runtime.
Advantages
The main advantage of dependency injection is it reduces coupling between classes and their dependencies.
Our code will become more reusable, testable, and maintainable since we don’t need to know and maintain how the dependencies are implemented.
This makes it more flexible to access the service and client objects.
Syncfusion’s .NET MAUI controls suite is the expert’s choice for building modern web apps.
Using dependency injections in a .NET MAUI app
I have a .NET MAUI app with a MainPage containing a Label and a ViewModel with the LabelText property. Refer to the following code example.
MainPage.xaml
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="DependencyInjectionInMAUI.MainPage"><Label VerticalTextAlignment="Center" HorizontalTextAlignment="Center" Text="{Binding LabelText}"/> </ContentPage>
ViewModel.cs
namespace DependencyInjectionInMAUI { public class ViewModel { public string LabelText { get; set; } = "Hello World"; } }
Let’s bind the LabelText property to the Label text using dependency injection by following these steps:
Step 1: Open the MauiProgram.cs file. Then, add a Microsoft.Extensions.DependencyInjection reference in it to access the service’s extension methods.
MauiProgram.cs
using Microsoft.Maui; using Microsoft.Maui.Hosting; using Microsoft.Maui.Controls.Compatibility; using Microsoft.Maui.Controls.Hosting; using Microsoft.Extensions.DependencyInjection;namespace DependencyInjectionInMAUI { public static class MauiProgram { public static MauiApp CreateMauiApp() { var builder = MauiApp.CreateBuilder(); builder .UseMauiApp<App>() .ConfigureFonts(fonts => { fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular"); });return builder.Build(); } } }
Step 2: Then, add the dependency injection singleton service for the MainPage and View model.
MauiProgram.cs
using Microsoft.Maui; using Microsoft.Maui.Hosting; using Microsoft.Maui.Controls.Compatibility; using Microsoft.Maui.Controls.Hosting; using Microsoft.Extensions.DependencyInjection;namespace DependencyInjectionInMAUI { public static class MauiProgram { public static MauiApp CreateMauiApp() { var builder = MauiApp.CreateBuilder(); builder .UseMauiApp<App>() .ConfigureFonts(fonts => { fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular"); });builder.Services.AddSingleton<MainPage>();builder.Services.AddSingleton<ViewModel>(); return builder.Build(); } } }
Every property of the Syncfusion .NET MAUI controls is completely documented to make it easy to get started.
Step 3: After successfully adding the necessary services as stated in step 2, you can directly access those objects in your desired class constructors. Therefore, access the MainPage and ViewModel service objects in the App.xaml.cs and MainPage.xaml.cs files respectively by adding arguments in the constructors of these classes.
Appxaml.cs
namespace DependencyInjectionInMAUI { public partial class App : Application { public App(MainPage mainPage) { InitializeComponent();MainPage = new MainPage(); } } }
MainPage.xaml.cs
namespace DependencyInjectionInMAUI { public partial class MainPage : ContentPage { public MainPage( ViewModel viewModel) { InitializeComponent(); }} }
Step 4: Now, get the service objects from the constructor argument and assign them to the client objects like in the following code.
Appxaml.cs
namespace DependencyInjectionInMAUI { public partial class App : Application { public App(MainPage mainPage) { InitializeComponent();MainPage = mainPage; } } }
MainPage.xaml.cs
namespace DependencyInjectionInMAUI { public partial class MainPage : ContentPage { public MainPage( ViewModel viewModel) { InitializeComponent();this.BindingContext = viewModel; }} }
That’s it. Now, run the program and see the result.
Syncfusion .NET MAUI controls allow you to build powerful line-of-business applications.
GitHub reference
For more details, refer to the complete example for dependency injection in a .NET MAUI application on GitHub. Supercharge your cross-platform apps with Syncfusion's robust .NET MAUI controls.
Conclusion
Thanks for reading! We hope you have learned how easy it is to work on a .NET MAUI app with the dependency injection technique. This makes our code easily reusable, testable, and maintainable. You can also use dependency injection in .NET MAUI apps that contain Syncfusion .NET MAUI controls. Every quarter we deliver more .NET MAUI controls to replace our existing Xamarin.Forms controls, so you can use them once you migrate to .NET MAUI projects.
If you have any feedback, special requirements, or controls that you’d like to see in our .NET MAUI suite, please mention them in the comments section below.
You can also contact us through our support forum, support portal, or feedback portal. We are always happy to assist you!
Related blogs
- What’s New in .NET MAUI: 2021 Volume 4
- How to Customize .NET MAUI Controls with Handler Architecture
- How to Reuse Xamarin.Forms Custom Renderers in .NET MAUI
- The All-New .NET MAUI Tab View Control Is Here
Comments (2)
hi
why when use dependency injection in Appxaml.cs the static resources in MainPage.xaml can’t be found
Hi,
I love DI in .NET MAUI. What I havent figured out yet if you can bind whole pages to AppShell. I can register them like this in my constructor, but how would I define those in the UI? is this the way to go? or is it unnecessary to bind whole pages because the AppShell would automatically bind pages that are in the container? I cant find anything about this in the docs…
MainPage Page;
MainPage1 Page1;
MainPage2 Page2;
public AppShell(MainPage page, MainPage1 page1, MainPage2 page2)
{
InitializeComponent();
Page = page;
Page1 = page1;
Page2 = page2;
}
Comments are closed.