dotnet/maui · error · InvalidOperationException
call Forms.Init() before this
Error message
call Forms.Init() before this
What it means
PageExtensions.CreateViewController requires the Forms platform layer to be initialized (Forms.IsInitialized) before it can build a view controller, because it needs registered renderers and the platform backend set up. Calling it before Forms.Init() means there is no platform context to create the controller from, so it throws InvalidOperationException. Forms.Init() is normally called in the AppDelegate/Program startup.
Source
Thrown at src/Compatibility/Core/src/MacOS/Extensions/PageExtensions.cs:11
using System;
using AppKit;
namespace Microsoft.Maui.Controls.Compatibility.Platform.MacOS
{
public static class PageExtensions
{
public static NSViewController CreateViewController(this Page view)
{
if (!Forms.IsInitialized)
throw new InvalidOperationException("call Forms.Init() before this");
if (!(view.RealParent is Application))
{
Application app = new DefaultApplication();
app.MainPage = view;
}
var result = new Platform();
result.SetPage(view);
return result.ViewController;
}
class DefaultApplication : Application
{
}
}
}View on GitHub (pinned to f377ff1c5e)
Solutions
- Call Forms.Init() in your NSApplicationDelegate before any CreateViewController call: Forms.Init(); var vc = page.CreateViewController();
- If in a test, call Forms.Init() (or the test host's equivalent) in the setup phase first.
- Reorder startup so Forms.Init() precedes the first CreateViewController.
Example fix
// before var vc = myPage.CreateViewController(); // throws: not initialized // after Forms.Init(); var vc = myPage.CreateViewController();
Defensive patterns
Strategy: validation
Validate before calling
if (!Forms.IsInitialized)
Forms.Init();
var vc = page.CreateViewController(); Type guard
static bool FormsReady() => Forms.IsInitialized;
Prevention
- Call Forms.Init() exactly once at app startup.
- In tests, initialize Forms in the setup fixture.
- Do not call CreateViewController from static initializers.
When it happens
Trigger: Invoking somePage.CreateViewController() (a macOS extension method) before Forms.Init() has run. Typically in a unit test, a non-standard host, or when CreateViewController is called from a static initializer / early startup path.
Common situations: Calling CreateViewController from a context that runs before the app delegate's FinishedLaunching/DidFinishLaunching calls Forms.Init(). Reusing the extension in a test harness that never calls Forms.Init(). Upgrading where the Init call was moved or removed.
Related errors
- application
- You MUST invoke LoadApplication () before calling base.Finis
- NavigationPage must have a root Page before being used. Eith
- NavigationPage must have a root Page before being used. Eith
- Please provide a main window in your app
AI-assisted analysis of dotnet/maui@f377ff1c5e (2026-08-13).
Data as JSON: /api/errors/080173d37a7bae93.
Report an issue: GitHub.