.netxamarinmaui

How to initialize NuGet package from MauiProgram.cs instead of platform-specific code in .NET MAUI?


I have a .NET MAUI nuget project where I need to initialize a NuGet package for Android. Currently, the package requires initialization inside MainActivity like this:

// MainActivity.cs (Android)
protected override void OnCreate(Bundle savedInstanceState)
{
    base.OnCreate(savedInstanceState);

    MyPackage.Init(this); // Passes Android context to package
}

This is mainly to set the application context for the package. However, I’d like to move this initialization to MauiProgram.cs so that it is not platform-specific, something like:

public static class MauiProgram
{
    public static MauiApp CreateMauiApp()
    {
        var builder = MauiApp.CreateBuilder();

        builder
            .UseMauiApp<App>()
            .UseMyPlugin(); // hypothetical method

        return builder.Build();
    }
}

Questions:

Additional Info:


Solution

  • You can just add a static registration class with an extension method somewhere in your shared code, e.g. like this:

    public static class Registration
    {
        public static MauiAppBuilder UseMyPlugin(this MauiAppBuilder builder)
        {
    #if ANDROID
            // add Android-specific registration code, e.g.
            MyPackage.Init(Microsoft.Maui.ApplicationModel.Platform.CurrentActivity);
            
    #elif IOS
            // add iOS-specific registration code...
    #endif
    
            return builder;
        }
    }
    

    This can then be called as you described:

    public static class MauiProgram
    {
        public static MauiApp CreateMauiApp()
        {
            var builder = MauiApp.CreateBuilder();
    
            builder
                .UseMauiApp<App>()
                .UseMyPlugin();
    
            return builder.Build();
        }
    }
    

    However, note that this strictly isn't necessary when you're not actually adding anything to the builder.

    You could also just create a simple static Initialize() method which doesn't hook into the builder:

    public class MyPackage
    {
        public static Initialize()
        {
    #if ANDROID
            // add Android-specific initialization code, e.g.
            MyPackage.Init(Microsoft.Maui.ApplicationModel.Platform.CurrentActivity);
            
    #elif IOS
            // add iOS-specific registration code...
    #endif
        }
    }
    

    and then call it from anywhere at the app start:

    MyPackage.Initialize();
    

    In both cases, you'll need some platform-specific methods to handle the initialization, e.g. in the Platforms folder or by using filename-based multi-targeting.