Skip to content
Dan Lorenz edited this page Nov 13, 2023 · 6 revisions

Shield MVVM - Setup

When setting up Shield MVVM, developers must call .UseMauiCommunityToolkit() on the MauiAppBuilder setup class first, then you can call .UseShieldMVVM(...). This method takes 2 parameters. The first sets up a callback to use the app's IoC container and the other is all the assemblies where Pages, Dialogs, and ViewModels are stored.

IoC Parameter

In order to avoid using the Service Locator anti-pattern and be tied to a specific IoC implementation, the first parameter is a function that takes a type and returns a dynamic instance. For the basic Microsoft implementation, a developer needs to define a static variable that has a reference to the IServiceProvider result. The code would look something like this:

 public static class MauiProgram
 {
     private static IServiceProvider ServiceProvider;

     public static MauiApp CreateMauiApp()
     {
         var builder = MauiApp.CreateBuilder();
         builder
             .UseMauiCommunityToolkit()
             .UseMauiApp<App>()
             .UseShieldMVVM(t => ServiceProvider.GetService(t), typeof(MauiProgram).Assembly)
             .ConfigureFonts(fonts =>
             {
                 fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
                 fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold");
             });

         var result = builder.Build();
         ServiceProvider = result.Services;
         return result;
     }
 }

Assemblies parameter

This takes a params array of Assembly classes. Developers need to pass in all assemblies that use ContentPageBase<>, DialogPageBase<>, and IViewModelBase so all Navigation-related classes are properly registered. IViewModelBase is implemented by PageViewModelBase and DialogViewModelBase.

UseShieldMVVMNoNavigation

If for some reason the default INavigationService doesn't work as needed, a developer can register INavigationService manually and call this method instead.

Clone this wiki locally