Home > Net >  Add MauiContext to Prism DI container in dotnet MAUI app
Add MauiContext to Prism DI container in dotnet MAUI app

Time:01-31

We have the following code in CreateMauiApp. We are trying to add a MauiContext object to the container so it is available in ViewModels via DI

 public static MauiApp CreateMauiApp()
 {
    var builder = MauiApp.CreateBuilder();
    // register types code etc
    MauiApp mauiApp = builder.Build();
    var mauiContext = new MauiContext(mauiApp.Services);
    builder.Services.AddSingleton(mauiContext);
    return mauiApp; 
 }

We are however unable to add mauiContext to the DryIoc container as the code throws an exception saying that the mauicontext type has not been registered. However we only get the mauicontext object after the registration of types has been done. Is it possible to get an instance of the container registry somehow? The below is not working

    var container = ContainerLocator.Container;
    var registry = container.Resolve<IContainerRegistry>();
    var mauiContext = new MauiContext(mauiApp.Services);
    registry.RegisterInstance(mauiContext);

CodePudding user response:

You can postpone the creation of the singleton instance to when it is actually injected:

var builder = MauiApp.CreateBuilder();

// this won't be null anymore when we actually use it
MauiCountext mauiContext = null;
builder.Services.AddSingleton( () => mauiContext );

MauiApp mauiApp = builder.Build();
mauiContext = new MauiContext(mauiApp.Services);
return mauiApp; 
  • Related