Xamarin shell 正在初始化 API 控制器

Xamarin shell initializing API Controller

我有一个 运行ning XF 应用程序,它通过 Azure API 进行大量数据库访问。到目前为止,一切都很好 运行ning。 由于布局更改,我更改为基于 shell 的导航。我完成了所有工作,但面临着一个巨大的问题。 我的 app.xaml.cs 装了很多控制器:

Public partical class App : Xamarin.Forms.Application, INotifyPropertyChanged {public static CampaignController CampaignController { get; private set; }}

并在 OnStart()

CampaignController = new CampaignController(new RestService());

在 public App() 中,我将 AppShell() 加载为 Mainpage

MainPage = new AppShell();

这是我的AppShell.xaml

<Shell xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         xmlns:local="clr-namespace:EY365OCMobileApp"
         x:Class="EY365OCMobileApp.AppShell">
<ShellContent Route="WelcomePage" ContentTemplate="{DataTemplate local:WelcomePage}">
    
</ShellContent>

WelcomePage.xaml.cs 看起来像这样:

protected async override void OnAppearing()
    {
        try
        {
            base.OnAppearing();
            Campaigns = await App.CampaignController.GetCampaignsAsync(364840001);
            CarouselView.ItemsSource = Campaigns;
            BindingContext = Campaigns;
        }
        catch (Exception ex)
        {
            await CreateNewBug.CreateANewBug(ex.Message,"Error in Module " + ex.Source,"\nMessage---\n{ 0}" + ex.Message + "\nInnerException---\n{ 0}" + ex.InnerException + "\nStackTrace---\n{ 0}" + ex.StackTrace + "\nTargetSite---\n{ 0}" + ex.TargetSite);
            ToastOptions toastOptions = Message.ShowMessage("An error was raised and a new bug created in our system.", "error");
            await this.DisplayToastAsync(toastOptions);
        }
    }

此行产生错误:

            Campaigns = await App.CampaignController.GetCampaignsAsync(364840001);

对象引用未设置到对象的实例。

当我调试时,app.xaml.cs 的初始化似乎没有 运行,因为它跳转到 AppShell.xaml.cs。当我将代码从 App.xaml.cs 移动到 AppShell.xaml.cs 时,它会带来同样的错误。 知道如何在 Xamarin 的 shell 环境中初始化休息服务控制器吗?

您可以在使用时延迟加载控制器。

应用

CampaignController _controller;
Public CampaignController controller{ 
   get
   {      
      if(_controller == null) 
      {
          _controller = new CampaignController(new RestService());
      }
      return _controller;  
   }
 }

欢迎页面

Campaigns = await (App.Current as App).controller.GetCampaignsAsync(364840001);
CarouselView.ItemsSource = Campaigns;