# .NET MAUI

Initialize AppPortal in native startup before MAUI, register the existing client in DI, track visible pages, and opt into Shell navigation timing.

Source: https://appportal.io/docs/sdks/dotnet/maui

This guide covers MAUI Android, iOS, Mac Catalyst and Windows WinUI heads.
Initialize AppPortal in the native entry point, before MAUI starts. The SDK owns the
runtime, storage, crash capture, lifecycle and app-start timing. MAUI dependency injection
registers that existing instance so application code can use interfaces and tests can supply mocks.

## 1. Install in the MAUI project

Install the public 3.0.384 release from NuGet.org:

```bash
dotnet add package AppPortal.Telemetry.Maui --version "3.0.384"
```

If AppPortal supplied a different release, use its package source and exact version.
See [version notes](https://appportal.io/docs/getting-started/documentation-versions) before updating an existing app.

Shared libraries using `IAppPortalClient` reference `AppPortal.Telemetry`; they do not initialize it.

## 2. Initialize in native startup

### Android

Update the constructor of your existing `MainApplication`:

```csharp
using Android.App;
using Android.Runtime;
using AppPortal;

[Application]
public class MainApplication : MauiApplication
{
    public MainApplication(IntPtr handle, JniHandleOwnership ownership)
        : base(AppPortalSdk.CreateBuilder("<app-credential>").Start(handle), ownership)
    {
    }

    protected override MauiApp CreateMauiApp() => MauiProgram.CreateMauiApp();
}
```

`Start(handle)` initializes from the existing native Application reference and returns it unchanged.
It runs while the base-constructor arguments are evaluated, before the MAUI base constructor.
The SDK borrows the reference; application code needs no JNI conversion or lifecycle forwarding.

Keep initialization in the native Application even when the app can launch only to do background
work. Such a launch may never create an Activity, a MAUI/Uno host, or a Prism container. That
background code can use the SDK directly; do not create a second runtime or wait for UI registration.

Cold-start timing begins at this native root before SDK runtime/storage recovery and ends at the
first Activity resume. MAUI application setup and any delay before MainActivity creation are included;
no application stopwatch or startup-complete callback is needed.

### iOS and Mac Catalyst

Initialize in `Program.Main` before UIKit creates the application and app delegate:

```csharp
using AppPortal;
using UIKit;

private static void Main(string[] args)
{
    AppPortalSdk.CreateBuilder("<app-credential>").Start();
    UIApplication.Main(args, null, typeof(AppDelegate));
}
```

The examples pass the app credential explicitly. If you instead add `appportal.credential` to
AndroidManifest metadata or `AppPortalCredential` to Info.plist, the parameterless builder can
discover it at the same native entry point.
Consent policy, optional features and endpoint overrides belong on this root builder.

### Windows

MAUI's Windows head normally generates `Main` from XAML. To initialize before its application
constructor, disable that generated entry point in the project file for Windows only:

```xml
<PropertyGroup Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'windows'">
  <DefineConstants>$(DefineConstants);DISABLE_XAML_GENERATED_MAIN</DefineConstants>
</PropertyGroup>
```

Add `Platforms/Windows/Program.cs`, using the namespace of your Windows `App` class:

```csharp
using AppPortal;
using Microsoft.UI.Dispatching;
using Microsoft.UI.Xaml;

namespace ExampleApp.WinUI;

internal static class Program
{
    [STAThread]
    private static void Main(string[] args)
    {
        WinRT.ComWrappersSupport.InitializeComWrappers();
        AppPortalSdk.CreateBuilder("<app-credential>").Start();
        Application.Start(_ =>
        {
            System.Threading.SynchronizationContext.SetSynchronizationContext(
                new DispatcherQueueSynchronizationContext(DispatcherQueue.GetForCurrentThread()));
            new App();
        });
    }
}
```

This retains the standard WinUI COM and dispatcher setup. Initialize COM wrappers before telemetry;
start telemetry before MAUI construction. Keep any existing custom activation/bootstrap work in
this entry point after the root call. The generated-main opt-out follows the [Windows App SDK entry-point pattern](https://learn.microsoft.com/en-us/windows/apps/windows-app-sdk/applifecycle/applifecycle-single-instance).

## 3. Register the existing instance in MauiProgram

```csharp
using Microsoft.Maui.Hosting;

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

`UseAppPortal()` registers `AppPortalSdk.Current` as `IAppPortalClient`. It does not initialize
telemetry, discover credentials, or create a second runtime. It lazily attaches visible-page
observation when MAUI attaches the application handler, without constructing the application early.
Disposing the MAUI container detaches page observers but does not stop the native owner.

SDK runtime configuration belongs on the native-startup builder, rather than a late MAUI
registration overload. The optional navigation configuration below does not change startup ownership. A missing native startup
leaves the injected client as a safe no-op; DI does not start the SDK later.

Inject `IAppPortalClient` into services or view models. The Microsoft DI helpers preserve an
existing mock registration. See [testing application code](https://appportal.io/docs/sdks/dotnet/telemetry#test-your-application-code).
Collection begins pending consent unless a saved decision or explicit initial policy applies;
connect the [consent decision](https://appportal.io/docs/sdks/dotnet/telemetry#connect-your-consent-ui).

## Observe native navigation RUM

`UseAppPortal()` automatically records the visible primary leaf page, including pages inside Shell,
NavigationPage, TabbedPage and FlyoutPage. You do not add calls to individual pages or view models.
Container pages, inactive tabs, nested region content and modal overlays do not replace the primary
screen. Each window has its own page history; reappearing on the same page instance does not create
another visit.

Page appearance records a screen visit. It does not invent request duration, cancellation, failure
or first-paint timing. To opt into Shell's separate navigation outcomes and timing, replace the
`builder.UseAppPortal()` statement in `CreateMauiApp` above with this call before `builder.Build()`:

```csharp
builder.UseAppPortal(trackShellNavigation: true);
```

Automatic page tracking still owns the single screen visit. Shell adds a navigation event and
measured `ScreenLoad` RUM when its start was observed. Timing ends at framework navigation
completion, not when rendering or deferred data loading finishes. Explicit Shell cancellation
never becomes a successful screen. Shell modal push/pop is overlay navigation and keeps the
primary page context.

Optional name mapping stays at the composition root. Use this replacement instead when you need
mapping; keep exactly one `UseAppPortal` call in `CreateMauiApp`:

```csharp
builder.UseAppPortal(trackShellNavigation: true, configureNavigation: options =>
{
    options.MapTargetName = pageType => pageType == "DetailsPage" ? "details" : pageType;
});
```

The mapper receives a page type name and runs on background work. Shell routes, query values,
navigation dictionaries, bindings and page state are not read. Deferred navigation keeps the
identity and observation time captured at its terminal callback; changing users before the worker
runs does not move that visit to the new user. Resetting or revoking consent invalidates older
pending observations, even if consent is granted again before they run.

The explicit `appShell.ObserveAppPortalNavigation()` and
`navigationPage.ObserveAppPortalNavigation()` APIs remain available. Retain and dispose their
handles with the host. A manually attached primary host suppresses automatic page capture for its
subtree. Choose builder Shell opt-in or manual Shell attachment rather than both.

If [Prism Regions](https://appportal.io/docs/sdks/dotnet/prism) represent the same primary navigation path, give that
adapter ownership and suppress the matching native surfaces at MAUI registration. Replace the
same `UseAppPortal` statement with this alternative:

```csharp
builder.UseAppPortal(trackShellNavigation: false, configureNavigation: options =>
    options.IgnoreSurface("page").IgnoreSurface("shell"));
```

Independent native pages and secondary/overlay Prism regions can coexist. The SDK cannot infer
that a named region and a native page mean the same screen. Prism MAUI page-stack navigation and
dialogs are separate from Region navigation.

Navigation breadcrumbs are buffered locally; they are not delivered with crashes. Navigation
events and RUM are separate delivered records. Use diagnostic logs for a visible lead-up trail.

## Verify the telemetry already being collected

With consent granted, run the app, navigate, then background and resume it. Open **Sessions** in
the Dashboard and select the run's **Session story**. Native root initialization provides lifecycle and
app-start context; page observation adds screens and optional Shell observation adds navigation timing. Supported managed
HTTP requests are measured automatically.

You do not need custom events to reconstruct this activity. Next, add diagnostic logs, report
managed exceptions your app catches, and record the outcomes you want to count. The
[shared telemetry guide](https://appportal.io/docs/sdks/dotnet/telemetry) shows where to get `IAppPortalClient`,
how to inject it, and how these signals appear on the session timeline.
