Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regarding Dependency Inject in dotnetmaui

Tags:

maui

I am converting my Xamarin Forms Application to #dotnetMAUI. In Xamarin I used dryloc for dependency injection. But since dependency injection was built in MAUI, I would like to use it. My question is, how can I configure a bunch of services and view models later into the container? My app is developed as a bunch of modules and initially, I just want to put the services and view models into the container that is required by the App's start-up page. SO that the start-up will be fast. In dryloc this was possible but I am not sure how to do it in the Maui app.

e.g.

I have two modules.

  1. Startup Module which contains only a startup page view model and its services.
  2. Chat Module which contains all the view models and services required for chat.

So, at first, I would like to configure the startup module in IOC container while creating the MAUI app.

And once the start-up page is open and the user clicks on something, I would like to put services and view models of the chat module into the IOC container.

In total, there are more than 200 services and view models in the app, and putting all those in the IOC container at the beginning might affect the start performance. In Xamarin Forms, It was the case and that is why I followed this approach.

like image 992
Pravin Patil Avatar asked Dec 27 '25 21:12

Pravin Patil


1 Answers

Unfortunately, adding to the ServiceCollection is not allowed after application is built.

Proof:

// In MauiProgram.cs:
public static IServiceCollection Services;

public static MauiApp CreateMauiApp()
{
    ...
    Services = builder.Services;
    return builder.Build();
}

// In MainPage.xaml.cs / OnAppearing:
MauiProgram.Services.AddSingleton<TestClass>();

Result is Exception:

System.InvalidOperationException
  HResult=0x80131509  
  Message=Cannot modify ServiceCollection after application is built.
  Source=Microsoft.Maui  
  StackTrace:
   at Microsoft.Maui.Hosting.MauiApplicationServiceCollection.CheckServicesAccess()  
   at Microsoft.Maui.Hosting.MauiApplicationServiceCollection.Add(ServiceDescriptor item)
   ...

Maui is making use of Dependency injection in .NET.

like image 74
ToolmakerSteve Avatar answered Dec 30 '25 22:12

ToolmakerSteve