Live Chat Icon For mobile
Live Chat Icon
Popular Categories.NET  (155).NET Core  (27).NET MAUI  (11)Angular  (51)ASP.NET  (48)ASP.NET Core  (68)ASP.NET MVC  (88)Azure  (29)Blazor  (114)DocIO  (21)Essential JS 2  (73)Essential Studio  (165)File Formats  (22)Flutter  (117)JavaScript  (153)Microsoft  (104)PDF  (59)React  (35)Succinctly series  (124)Syncfusion  (504)TypeScript  (30)Uno Platform  (3)UWP  (4)Vue  (28)Webinar  (27)Windows Forms  (57)WinUI  (32)WPF  (127)Xamarin  (134)XlsIO  (24)Other CategoriesBarcode  (4)BI  (29)Bold BI  (4)Build conference  (6)Business intelligence  (53)Button  (4)C#  (111)Chart  (54)Cloud  (10)Company  (445)Dashboard  (6)Data Science  (3)Data Validation  (5)DataGrid  (51)Development  (273)Doc  (7)DockingManager  (1)eBook  (94)Enterprise  (22)Entity Framework  (5)Essential Tools  (14)Excel  (21)Extensions  (16)File Manager  (4)Gantt  (9)Gauge  (8)Git  (4)Grid  (27)HTML  (9)Installer  (2)Knockout  (2)Language  (1)LINQPad  (1)Linux  (2)M-Commerce  (1)Metro Studio  (11)Mobile  (246)Mobile MVC  (9)OLAP server  (1)Open source  (1)Orubase  (12)Partners  (21)PDF viewer  (26)Performance  (7)PHP  (1)PivotGrid  (4)Predictive Analytics  (6)Report Server  (3)Reporting  (10)Reporting / Back Office  (11)Rich Text Editor  (6)Road Map  (9)Scheduler  (29)SfDataGrid  (9)Silverlight  (21)Sneak Peek  (19)Solution Services  (2)Spreadsheet  (11)SQL  (7)Stock Chart  (1)Surface  (4)Tablets  (5)Theme  (11)Tips and Tricks  (71)UI  (148)Uncategorized  (68)Unix  (2)User interface  (68)Visual State Manager  (1)Visual Studio  (22)Visual Studio Code  (13)Web  (237)What's new  (158)Windows 8  (19)Windows App  (1)Windows Phone  (15)Windows Phone 7  (9)WinRT  (26)
Share on twitter
Share on facebook
Share on linkedin
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.

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

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

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!

Related blogs

Tags:

Share this post:

Share on twitter
Share on facebook
Share on linkedin
Popular Now

Be the first to get updates

Subscribe RSS feed
Scroll To Top