Learn How to Use Dependency Injection in .NET MAUI
Tags: dotnet, csharp, productivity, mobile
Published: 2021-12-23 04:56:18

---
title: Learn How to Use Dependency Injection in .NET MAUI
published: true
date: 2021-12-22 11:53:40 UTC
tags: dotnet, csharp, productivity, mobile
canonical_url: https://www.syncfusion.com/blogs/post/learn-how-to-use-dependency-injection-in-net-maui.aspx
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xczib4xe3kpg0gw7ogci.png
---

As you know, [.NET MAUI](https://docs.microsoft.com/en-us/dotnet/maui/what-is-maui "Documentation link to .NET MAUI") evolved from [Xamarin.Forms](https://en.wikipedia.org/wiki/Xamarin "Link to Wikipedia page for Xamarin") with a better developer experience and better performance. Like adding a gem to a crown, .NET MAUI allows the use of [dependency injection](https://en.wikipedia.org/wiki/Dependency_injection "Link to Wikipedia page for 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](https://en.wikipedia.org/wiki/Inversion_of_control "Link to Wikipedia page for 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.

## **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**

```html
<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**

```csharp
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**

```csharp
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**

```csharp
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();
}
}
}
```

**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**

```csharp
namespace DependencyInjectionInMAUI
{
public partial class App : Application
{
public App(MainPage mainPage)
{
InitializeComponent();MainPage = new MainPage();
}
}
}
```

**MainPage.xaml.cs**

```csharp
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**

```csharp
namespace DependencyInjectionInMAUI
{
public partial class App : Application
{
public App(MainPage mainPage)
{
InitializeComponent();MainPage = mainPage;
}
}
}
```

**MainPage.xaml.cs**

```csharp
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.

![Object binding using Dependency Injection](https://www.syncfusion.com/blogs/wp-content/uploads/2021/12/Object-binding-using-Dependency-Injection.png)
<figcaption>Object Binding Using Dependency Injection</figcaption>

## GitHub reference

For more details, refer to the complete example for [dependency injection in a .NET MAUI application on GitHub](https://github.com/SyncfusionExamples/dependency-injection-in-maui "Link to dependency injection in .NET MAUI app GitHub demo").

## 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](https://www.syncfusion.com/maui-controls "Link to .NET MAUI Controls") controls. Every quarter we deliver more .NET MAUI controls to replace our existing [Xamarin.Forms](https://www.syncfusion.com/xamarin-ui-controls "Link to Xamarin UI controls") 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](https://www.syncfusion.com/forums "Link to the Syncfusion support forum"), [support portal](https://support.syncfusion.com/ "Link to the Syncfusion support portal"), or [feedback portal](https://www.syncfusion.com/feedback/xamarin-forms "Link to Syncfusion Feedback Portal"). We are always happy to assist you!

## Related blogs

- [What’s New in .NET MAUI: 2021 Volume 4](https://www.syncfusion.com/blogs/post/whats-new-in-net-maui-2021-volume-4.aspx "Link to What’s New in .NET MAUI: 2021 Volume 4 blog")
- [How to Customize .NET MAUI Controls with Handler Architecture](https://www.syncfusion.com/blogs/post/how-to-customize-net-maui-controls-with-handler-architecture.aspx "Link to How to Customize .NET MAUI Controls with Handler Architecture blog")
- [How to Reuse Xamarin.Forms Custom Renderers in .NET MAUI](https://www.syncfusion.com/blogs/post/how-to-reuse-xamarin-forms-custom-renderers-in-net-maui.aspx "Link to How to Reuse Xamarin.Forms Custom Renderers in .NET MAUI blog")
- [The All-New .NET MAUI Tab View Control Is Here](https://www.syncfusion.com/blogs/post/the-all-new-net-maui-tab-view-control-is-here.aspx "Link to The All-New .NET MAUI Tab View Control Is Here blog")