0

In my MAUI application, I like to redirect the user to a different page rather than MainPage in particular condition. For example,

public partial class App : Application
{
    public App(UserSettings settings, Database database)
    {
        InitializeComponent();

        long id = settings.DefaultPage;
        if (id == 0)
            MainPage = new AppShell();
        else
            MainPage = new MyPage(new MyPageViewModel(database) { Id = id });
    }
}

The MyPage has a parameter Id defined like

[QueryProperty("Id", "Id")]
public partial class MyPage: ContentPage {
    public MyPage(MyPageViewModel model)
    {
        InitializeComponent();

        vm = model;
        BindingContext = vm;
    }

    long _id;
    public long Id
    {
        get => _id;
        set
        {
            _id = value;
            vm.Init(_id);
        }
    }
}

Is there a way - correct way - to set up the MainPage without creating a new model by using the dependency inject? How can I set a page with parameters as a MainPage?

Mustafa Özçetin
  • 1,893
  • 1
  • 14
  • 16
Enrico
  • 3,592
  • 6
  • 45
  • 102

1 Answers1

0
  • Inject the ServiceProvider into App constructor.
  • Request the page from the ServiceProvider.
  • Manipulate as desired.
  • Finally, set MainPage.
public partial class App : Application
{
    public App(IServiceProvider services, UserSettings settings, Database database)
    {
        InitializeComponent();

        ...
        else
        {
            // This creates the page, and its dependencies.
            var page = services.GetService<MyPage>();
            page.Id = id;
            page.vm.Database = database;   // or whatever
            MainPage = page;
       }
   }
}

Answers here give more information about using ServiceProvider directly, when Dependency Injection isn't suitable.

Including optionally saving services in an app static, for usage throughout the app:

public static IServiceProvider Services;

public App(IServiceProvider services)
{
    Services = services; 
...

Usage elsewhere in app:

var something = App.Services.GetService<SomeTypeName>();
ToolmakerSteve
  • 18,547
  • 14
  • 94
  • 196