在 Microsoft.Maui.Controls.Application 中从 IServiceProvider 解析 MainPage

Resolve MainPage from IServiceProvider in Microsoft.Maui.Controls.Application

我创建了一个新的 dotnet maui 项目并想从 IServiceProvider 解析 MainPage

我在 MauiProgram.cs 中添加了行 builder.Services.AddSingleton<MainPage>();。而不是 (App.xaml.cs):

    public partial class App : Microsoft.Maui.Controls.Application
    {
        public App()
        {
            InitializeComponent();
            MainPage = new MainPage();
        }
    }

我想检索或以某种方式访问​​ MauiApp 以从 IServiceProvider 解析 MainPage。类似的东西:

    public partial class App : Microsoft.Maui.Controls.Application
    {
        public App()
        {
            InitializeComponent();
            var mauiApp = (MauiApp)this;
            MainPage = mauiApp.Services.GetService(typeof(MainPage)) as ContentPage;
        }
    }

最好的方法是什么?

在MauiProgram.cs中:

为您需要的任何服务添加单例:

   public static MauiApp CreateMauiApp()
    {
       builder.Services.AddSingleton<MainPage>();
       builder.Services.AddSingleton<IGoodbyeWorldService, GoodbyeWorldService>();
    }

在App.Xaml.cs中:

在 App 方法的参数中包含 MainPage 并分配给 MainPage:

    public App(MainPage page) 
    {
        InitializeComponent();
        MainPage = page;
    }

然后在MainPage.xaml.cs参数中包含您需要的服务:

    public MainPage(IGoodbyeWorldService service)
    {
     InitializeComponent();
     lblOne.Text = service.SayGoodbye();
    }