Learn How to Use Dependency Injection in .NET MAUI | Syncfusion Blogs
Live Chat Icon For mobile
Live Chat Icon
Popular Categories.NET  (173).NET Core  (29).NET MAUI  (199)Angular  (107)ASP.NET  (51)ASP.NET Core  (82)ASP.NET MVC  (89)Azure  (40)Black Friday Deal  (1)Blazor  (211)BoldSign  (13)DocIO  (24)Essential JS 2  (106)Essential Studio  (200)File Formats  (63)Flutter  (132)JavaScript  (219)Microsoft  (118)PDF  (80)Python  (1)React  (98)Streamlit  (1)Succinctly series  (131)Syncfusion  (892)TypeScript  (33)Uno Platform  (3)UWP  (4)Vue  (45)Webinar  (50)Windows Forms  (61)WinUI  (68)WPF  (157)Xamarin  (161)XlsIO  (35)Other CategoriesBarcode  (5)BI  (29)Bold BI  (8)Bold Reports  (2)Build conference  (8)Business intelligence  (55)Button  (4)C#  (146)Chart  (127)Cloud  (15)Company  (443)Dashboard  (8)Data Science  (3)Data Validation  (8)DataGrid  (62)Development  (618)Doc  (8)DockingManager  (1)eBook  (99)Enterprise  (22)Entity Framework  (5)Essential Tools  (14)Excel  (37)Extensions  (22)File Manager  (6)Gantt  (18)Gauge  (12)Git  (5)Grid  (31)HTML  (13)Installer  (2)Knockout  (2)Language  (1)LINQPad  (1)Linux  (2)M-Commerce  (1)Metro Studio  (11)Mobile  (497)Mobile MVC  (9)OLAP server  (1)Open source  (1)Orubase  (12)Partners  (21)PDF viewer  (42)Performance  (12)PHP  (2)PivotGrid  (4)Predictive Analytics  (6)Report Server  (3)Reporting  (10)Reporting / Back Office  (11)Rich Text Editor  (12)Road Map  (12)Scheduler  (52)Security  (3)SfDataGrid  (9)Silverlight  (21)Sneak Peek  (31)Solution Services  (4)Spreadsheet  (11)SQL  (10)Stock Chart  (1)Surface  (4)Tablets  (5)Theme  (12)Tips and Tricks  (112)UI  (379)Uncategorized  (68)Unix  (2)User interface  (68)Visual State Manager  (2)Visual Studio  (31)Visual Studio Code  (17)Web  (582)What's new  (319)Windows 8  (19)Windows App  (2)Windows Phone  (15)Windows Phone 7  (9)WinRT  (26)
Learn How to Use Dependency Injection in .NET MAUI

Learn How to Use Dependency Injection in .NET MAUI

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.

Object binding using Dependency Injection
Object Binding Using Dependency Injection

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.

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 forumsupport portal, or feedback portal. We are always happy to assist you!

Test Flight
App Center Badge
Google Play Store Badge
Microsoft Badge
Github Store Badge

Related blogs

Tags:

Share this post:

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.

Popular Now

Be the first to get updates

Subscribe RSS feed

Be the first to get updates

Subscribe RSS feed