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:
- Is there a way to pass the Android Context from MauiProgram.cs without touching MainActivity?
- Can I write a .UseMyPlugin() extension method that works cross-platform, but still sets the context correctly for Android?
- Is there a recommended approach in MAUI to centralize such platform-specific initialization?
Additional Info:
- Target frameworks: .NET 8
- Package requires Android Context during initialization.
- I want to avoid having multiple platform-specific Init() calls if possible.