Skip to content

Architecture

Michael Riddle edited this page Aug 19, 2026 · 14 revisions

Architecture

How KHost Cue is put together: the MAUI Blazor Hybrid shell, the six-project layering, the service inventory, and app lifecycle/session state. This page is developer-facing — for build/test commands see Building & testing, for coding conventions see Conventions.

What a MAUI Blazor Hybrid app is here

KHost Cue is a native app (a real Android Activity / iOS UIApplicationDelegate / Windows/Catalyst app) that hosts its entire UI in a BlazorWebView — a WebView control pointed at the app's own bundled wwwroot, running the Razor components in-process. There is no HTTP round-trip between the UI and the C# it calls: Blazor Hybrid runs the same .NET runtime as the native app, in the same process, and a component's @code block calls a service directly. MainPage.xaml is a single-page native shell (src/KHost.Mobile/MainPage.xaml, MainPage.xaml.cs) wrapping one BlazorWebView; routing between "pages" is Blazor's own Router (Components/Routes.razor, in KHost.Mobile.UI), not native navigation.

The Razor components and their local stores are one shared Razor/C# codebase across iOS and Android, with a native shell (KHost.Mobile) for platform integration — back-button handling, safe-area insets, haptics, the QR scanner, native HTTP stack. Three kinds of code run:

  • C# in-process — the Razor components, stores and models across every project: runs on the same runtime as the native shell, no serialization boundary.
  • JS interop — wwwroot/js/*.js, one module per feature (swipe.js, album-art.js, insets.js, theme.js, sheet.js, …), for things only the DOM/WebView can do: gesture recognition, IntersectionObserver-driven visibility, blob: object URLs, CSS variable pushes. Bound once via window.kh<Feature>.register(...); C#↔JS round-trips use DotNetObjectReference + [JSInvokable] (see Conventions → Blazor component pattern).
  • No HTTP to a first-party server — the app is local/offline only. The only outbound HTTP is to third-party keyless APIs (iTunes, Deezer, LRCLIB, GitHub Releases, the Spotify/YouTube Music public embed/playlist endpoints) via KHost.Mobile.Clients.

The eight projects

Six shipping projects under src/ plus two test projects under tests/, layered so that only KHost.Mobile (the head) knows MAUI exists. Each references only what sits above it.

src/     KHost.Mobile, .UI, .Abstractions, .Common, .Infrastructure, .Clients
tests/   KHost.Mobile.UnitTests, .IntegrationTests
Project References Role
KHost.Mobile.Abstractions nothing Every contract, model, DTO and exception, and nothing that implements one: the store and platform interfaces (Services/), the entities (Models/), and the client capability contracts (Clients/Metadata/, CoverArt/, Lyrics/, Updates/, plus the Spotify/YouTubeMusic import interfaces and DTOs). Zero packages.
KHost.Mobile.Common nothing Generic, domain-free helpers — currently JsonElementExtensions (Json/), null-safe JsonElement navigation used by the client parsers. Nothing here may reference a domain concept (track, singer, venue) or a specific backend; helpers with domain shape belong in KHost.Mobile.Clients. Pure BCL: no project references, no packages, public API.
KHost.Mobile.Infrastructure Abstractions Every MAUI-free implementation. Services/ holds all of them — the JSON stores, AppSession, AlbumArtCache, VenueLocator, BackButtonService, SafeAreaInsets, AtomicFileWriter, QrCodeService, RatingScorer, SurprisePicker, TimeFormatter, AppVersionParser, DateTimeInputConverter, SingerProfileCodec, SingerFileNames, SongLinkBuilder, KaraFunVenueUrlParser, SongEnricher — alongside Serialization/ (the JsonSerializerContext partials) and Diagnostics/ (LoggingHttpMessageHandler). Every concrete type is internal sealed; only JsonFileStore<T>, the store base class, is public. Project.cs (AddKHostInfrastructure) is the sole way a consumer gets any of them registered.
KHost.Mobile.Clients Abstractions, Common The vendor backends only — Apple/ (iTunes metadata), Deezer/ (cover-art + spelling fallback), LrcLib/ (lyrics), GitHub/ (Releases update check), Spotify/ and YouTubeMusic/ (playlist import), plus the internal Matching/ helpers they share. MAUI-free; references Microsoft.Extensions.Http so Project.cs (AddKHostClients) can register its own typed HttpClients — its only package reference. Every backend/parser class is internal sealed.
KHost.Mobile.UI Abstractions, Common, Infrastructure, Clients A plain net10.0 Razor class library, no MAUI workload: the Razor components (Components/) and Services/AlbumArtService.cs. Because the workload is absent, a component cannot reference a MAUI type at all — the layering rule is enforced by the compiler, not by review. Project.cs (AddKHostUI) registers IAlbumArtService.
KHost.Mobile all of the above The MAUI Blazor Hybrid head: MauiProgram.cs, App.xaml, MainPage.xaml, Platforms/, Resources/, wwwroot/, and Services/ — the Maui* platform adapters plus QrScanPage. The only project with the MAUI workload; the project is itself named KHost.Mobile, so no AssemblyName pin is needed.
KHost.Mobile.UnitTests / .IntegrationTests Abstractions, Common, Infrastructure, Clients Plain net10.0, so they reference projects directly rather than linking source files. Neither references KHost.Mobile.UI or the head.

The rule the layering enforces: a plain net10.0 library can be referenced from the MAUI head, never the reverse. KHost.Mobile.Clients takes its HttpClient by injection rather than newing one; base address, headers and the logging handler are configured at the DI registration site (MauiProgram.cs's call into AddKHostClients), not inside the library.

Rules for moving a type between projects:

  • A namespace names its assembly: Infrastructure/Services/ is KHost.Mobile.Infrastructure.Services. No project sets RootNamespace. An interface and its implementation sit in different namespaces (Abstractions.Services.ISongListStore vs Infrastructure.Services.JsonFileSongListStore), so a consumer of both imports both.
  • The Maui prefix is a claim: it means the type touches the workload and cannot move below KHost.Mobile. Every file in src/KHost.Mobile/Services/ genuinely binds to MAUI; anything that doesn't belongs one layer down.
  • Implementations are internal: every Clients backend/parser and every Infrastructure Services/Logic/Search type is internal sealed, exposed only through its Abstractions interface. Both projects declare <InternalsVisibleTo> for KHost.Mobile.UnitTests and KHost.Mobile.IntegrationTests, so the test suites reach them directly. BackButtonOverlayGuard (constructed by components) and JsonFileStore<T> (the store base class) stay public on purpose.

ApplicationId (khost.mobile) is a separate setting from the assembly name — it is what identifies the app to a device; moving it turns an update into an uninstall that wipes user data.

Target frameworks

<TargetFrameworks>net10.0-android</TargetFrameworks>
<TargetFrameworks Condition="!$([MSBuild]::IsOSPlatform('linux'))">$(TargetFrameworks);net10.0-ios</TargetFrameworks>
<TargetFrameworks Condition="$([MSBuild]::IsOSPlatform('windows'))">$(TargetFrameworks);net10.0-windows10.0.19041.0</TargetFrameworks>
<TargetFrameworks Condition="$([MSBuild]::IsOSPlatform('osx'))">$(TargetFrameworks);net10.0-maccatalyst</TargetFrameworks>

(src/KHost.Mobile/KHost.Mobile.csproj)

Head Built where Purpose
net10.0-android Any OS The shipping Android target; the green signal on Windows (iOS can't build there).
net10.0-ios macOS only (needs a paired Mac) The shipping iOS target.
net10.0-windows10.0.19041.0 Windows only Fast Blazor-UI iteration with no emulator (dotnet run).
net10.0-maccatalyst macOS only The Mac equivalent of the Windows head — dev-only layout preview, no shipping product; pinned to the 393×852 mobile-preview viewport by App.PinToMobilePreviewViewport (src/KHost.Mobile/App.xaml.cs).

Restore evaluates every declared TFM even when you build a single head with -f. A build of just net10.0-android still fails at restore until the iOS/Windows/Catalyst workloads (whichever the OS condition adds) are installed — dotnet workload restore src/KHost.Mobile/KHost.Mobile.csproj installs exactly the declared set. MauiVersion is pinned to 10.0.80 in the csproj — the workload-default 10.0.20 causes a known Android 16 launch crash — see Building & testing for the full gotcha.

Service inventory

Every row below is registered in src/KHost.Mobile/MauiProgram.cs, mostly by its call into AddKHostInfrastructure(), AddKHostUI() and AddKHostClients(...) (see Conventions → Project.cs). All local stores follow the interface-first pattern in Conventions (see Layering rules, next section).

Interface Implementation Lifetime Job
IAppDataDirectory MauiAppDataDirectory Singleton Resolves the private data folder path; abstracted so stores stay unit-testable off-device.
ISongListStore JsonFileSongListStore Singleton The wishlist (SongListItems), namespaced per singer (song-list-{id}.json). Deliberately registered twice — as itself and as ISongListStore, resolving to the same instance — so the profile export/import path and every interface consumer share one cache. Not a redundant registration; collapsing it splits the cache.
ITonightStore JsonFileTonightStore Singleton The on-deck set list (TonightEntrys), namespaced per singer (tonight-{id}.json).
IVenueStore JsonFileVenueStore Singleton Saved venues (shared across singers).
ISingerStore JsonFileSingerStore Singleton The device's singer roster; seeds the default singer on a fresh install.
ILocationProvider MauiLocationProvider Singleton Best-effort device location via MAUI Geolocation.
IVenueLocator VenueLocator Singleton Turns a location fix into the nearest saved venue and sets it active.
IAppSettings MauiAppSettings Singleton Every user-facing toggle/tunable, persisted via MAUI Preferences.
IAppSession AppSession Singleton Ephemeral per-launch state — active singer/venue, smart-landing/tutorial resolution, per-singer My Songs view state. Never persisted.
ILyricsCache JsonFileLyricsCache Singleton On-device cache of LRCLIB lyrics lookups.
IAlbumArtCache AlbumArtCache Singleton Downloads/caches cover-art bytes to disk; pulls a pooled HttpClient per download.
IAlbumArtService AlbumArtService Scoped Per-song cover view + fetch orchestration for the WebView. See exception below.
ILinkLauncher MauiLinkLauncher Singleton Opens a URL outside the WebView (YouTube/Spotify quick links).
IHaptics MauiHaptics Singleton Short confirm-vibration for press-and-hold gestures.
ISafeAreaInsets SafeAreaInsets Singleton Holds the measured system-bar/cutout insets (Android only needs this; iOS's WebView surfaces env() natively).
IBackButtonService BackButtonService Singleton Registry the Android back button consults to close the top-most open overlay instead of navigating.
IQrScanner MauiQrScanner (Android/iOS) / UnsupportedQrScanner (other heads) Singleton Native QR scan for the KaraFun venue link. Carries IsSupported, so a caller asks "can this device scan" rather than branching on platform; the Windows/Catalyst stub returns false/null and keeps DI resolvable everywhere.
IQrCodeService QrCodeService Singleton Encodes text as QR-code SVG, on-device. Stateless; the only type naming the encoder package, so a different backend is a one-class swap.
IAppVersionInfo MauiAppVersionInfo Singleton The running build's own ApplicationDisplayVersion, named apart from MAUI Essentials' IAppInfo to avoid a global-using collision (same trap as IHaptics).
IFileExchange MauiFileExchange Singleton Profile export/import through the platform's file picker and share sheet.
IAtomicFileWriter AtomicFileWriter Singleton Crash-safe .tmp-then-rename writes and .corrupt-sibling quarantine; the one path every store's bytes reach disk through.
ISongLinkBuilder SongLinkBuilder Singleton Builds the KaraFun/Spotify/YouTube quick-search links for a song — one builder for all three targets.
IKaraFunVenueUrlParser KaraFunVenueUrlParser Singleton Parses a scanned/pasted KaraFun venue URL into its venue id.
ITimeFormatter TimeFormatter Singleton Relative/duration time-string formatting for the UI.
IAppVersionParser AppVersionParser Singleton Parses/compares version strings (tolerates a pre-release suffix) for the update check.
IDateTimeInputConverter DateTimeInputConverter Singleton Converts between <input type="datetime-local"> text and DateTimeOffset.
IRatingScorer RatingScorer Singleton The Bayesian how-it-went star score, from RatingConfig/RatingContext.
ISurprisePicker SurprisePicker Singleton Weighted-random pick for the 🎲 Surprise draw, from SurpriseOptions.
ISingerProfileCodec SingerProfileCodec Singleton Encodes/decodes a SingerProfile export, detecting ProfileFileKind on import.
ISingerFileNames SingerFileNames Singleton Builds a singer's per-singer file names (song-list-{id}.json, tonight-{id}.json).
ISongEnricher SongEnricher Singleton Decides what a song's one-shot catalogue lookup fills in and which source is asked in what order — iTunes first, Deezer only as a fallback. Returns what to apply rather than writing to the song, so an abandoned lookup leaves nothing half-applied.
IYouTubeMusicImportService YouTubeMusicImportService (Clients) Typed HTTP client Public YouTube Music playlist import.
ISpotifyImportService SpotifyImportService (Clients) Typed HTTP client Public Spotify playlist import.
ILookupOptions AppLookupOptions Singleton Bridges the settings-backed catalogue region into Clients, which can't read IAppSettings itself.
ITrackMetadataLookup ITunesTrackMetadataLookup (Clients) Typed HTTP client Year/genre/cover-art-URL auto-fill (iTunes Search API).
ICoverArtLookup DeezerCoverArtLookup (Clients) Typed HTTP client Cover-art fallback when iTunes returns none.
ISpellingSuggestionLookup DeezerSpellingSuggestionLookup (Clients) Typed HTTP client Spelling-suggestion fallback when iTunes offers neither a match nor a correction.
(named client "album-art") — Named HTTP client Cover-image byte downloads for IAlbumArtCache (20 s timeout).
ILyricsLookup LrcLibLyricsClient (Clients) Typed HTTP client LRCLIB lyrics lookup.
IUpdateLookup GitHubReleaseClient (Clients) Typed HTTP client Reads this repo's GitHub Releases feed.
IAppUpdateService MauiAppUpdateService Singleton Once-per-launch "is there a newer version?" check + session dismissal.

IAlbumArtService is registered AddScoped, not AddSingleton. It talks to the WebView through IJSRuntime, which is scoped in Blazor Hybrid (one DI scope per BlazorWebView). A singleton registration would capture whichever IJSRuntime resolved first, and every JS transfer would silently fail (the object-URL calls in wwwroot/js/album-art.js never reach the live WebView). The app has exactly one BlazorWebView, so the scoped instance is shared by My Songs and Tonight. IAlbumArtCache (the disk-cache layer underneath it, no JS interop) stays a plain singleton.

Layering rules

  • Every JSON store derives from JsonFileStore<TItem, TCache> (Infrastructure/Services/), which owns the gate, the in-memory cache, the crash-safe write and the corrupt-file quarantine. A subclass supplies its serializer context, a label, and its file path; per-singer stores also supply the active-singer key. It is the only production caller of IAtomicFileWriter, so every byte the app persists goes through one crash-safe path.
  • Interface-first local stores. Every local store (ISongListStore, ITonightStore, IVenueStore, ISingerStore, ILyricsCache) is bound to a JSON-file implementation, with UI code depending only on the interface — pages never name a concrete store type, and the concrete stores are internal so it couldn't anyway.
  • Logging in Infrastructure and UI. ILogger<T> is injected via primary constructor; KHost.Mobile.Clients has no logging, and KHost.Mobile.Abstractions takes no package reference at all. Providers are #if DEBUG-gated in src/KHost.Mobile/MauiProgram.cs (Debug → Android logcat via AndroidLogcatLoggerProvider, src/KHost.Mobile/Platforms/Android/AndroidLogcatLoggerProvider.cs; Release stays quiet).
  • LoggingHttpMessageHandler chains onto every typed HTTP client (src/KHost.Mobile.Infrastructure/Diagnostics/), registered once as AddTransient<LoggingHttpMessageHandler>() and attached via a configureHandler callback that MauiProgram.cs passes into AddKHostClients(...), plus directly on the "album-art" named client. It's the one seam that captures what the native platform HTTP stack actually sent and received on-device (WinHTTP / NSURLSession / Android's HTTP stack differ from what .NET's abstractions show you).

App lifecycle & session state

  • Bootstrap sequencing. MainLayout.razor (src/KHost.Mobile.UI/Components/Layout/) gates the whole shell behind _ready: OnInitializedAsync calls ISingerStore.EnsureSeededAsync() (seeds a default singer on first run), resolves the active singer from IAppSettings.LastActiveSingerId (falling back to the first singer), and calls IAppSession.SetActiveSinger(...) — only then does it render the header/content/nav. The per-singer song-list/tonight stores read the active singer id to pick their file, so it must be set before any personal page loads.
  • IAppSession (src/KHost.Mobile.Abstractions/Services/IAppSession.cs, impl AppSession) holds everything ephemeral and per-launch, never persisted: LandingResolved/TutorialResolved (one-time-per-launch guards), MySongsViewFor(singerId) (per-singer filter/sort/scroll state, since the page component itself is disposed on navigation), ActiveVenueId/ActiveVenuePinned, and ActiveSingerId — each with a Changed event the UI subscribes to.
  • Smart landing. The first time My Songs loads in a session, it checks IAppSession.LandingResolved; if unset, it routes to Tonight when a set is already queued, else stays on My Songs, then sets LandingResolved = true so later navigation is never bounced. Configurable via IAppSettings.LaunchDestination ("smart" / "songs" / "tonight").
  • IBackButtonService / BackButtonOverlayGuard. Components that own a dismissible overlay (a sheet, the header ⋮ menu) register a close-callback via BackButtonOverlayGuard while mounted; MainActivity.OverlayBackPressedCallback (src/KHost.Mobile/Platforms/Android/MainActivity.cs) consults IBackButtonService.HandleBack() on every hardware/gesture back press, closing the newest-registered overlay instead of minimizing the app. Two back presses with nothing left open triggers a "press back again to exit" toast within a 2 s window. The service is a no-op on iOS (no hardware back button) but still resolves via DI so shared components stay platform-agnostic.
  • ISafeAreaInsets. Android's WebView never populates CSS env(safe-area-inset-*), so MainActivity.InsetPublisher measures the system-bars ∪ display-cutout union on every window-insets pass and calls ISafeAreaInsets.Set(top, bottom); MainLayout.OnAfterRenderAsync pushes those values into the --kh-inset-* CSS variables via khInsets.set (wwwroot/js/insets.js). iOS never pushes (values stay 0), so the CSS max() falls through to the native env() there instead.

Diagram

flowchart TB
    subgraph Native["Native shell (per-platform head)"]
        MainActivity["MainActivity.cs (Android)<br/>AppDelegate.cs (iOS/Catalyst)"]
        BackCB["OverlayBackPressedCallback"]
        Insets["InsetPublisher"]
    end

    subgraph WebView["BlazorWebView (in-process, wwwroot origin)"]
        Components["Components/*.razor<br/>(Pages, Layout, sheets)"]
        JS["wwwroot/js/*.js<br/>swipe, album-art, insets, sheet, theme"]
    end

    subgraph Services["Infrastructure + UI services (wired in MauiProgram.cs)"]
        Stores["ISongListStore / ITonightStore /<br/>IVenueStore / ISingerStore / ILyricsCache"]
        Session["IAppSession / IAppSettings"]
        Platform["IHaptics / IQrScanner /<br/>ISafeAreaInsets / IBackButtonService"]
        AlbumArt["IAlbumArtService (scoped) →<br/>IAlbumArtCache (singleton)"]
    end

    subgraph Clients["KHost.Mobile.Clients (MAUI-free)"]
        Lookups["ITrackMetadataLookup (iTunes)<br/>ICoverArtLookup / ISpellingSuggestionLookup (Deezer)<br/>ILyricsLookup (LRCLIB) / IUpdateLookup (GitHub)"]
    end

    subgraph Disk["Device storage"]
        JSON["FileSystem.AppDataDirectory/*.json<br/>song-list-{id}.json, tonight-{id}.json, venues.json,<br/>singers.json, lyrics-cache.json<br/>(settings live in MAUI Preferences, not a JSON file)"]
        ArtCache["album-art/*"]
    end

    Net(("Third-party APIs<br/>(keyless, best-effort)"))

    Components <--> JS
    Components --> Stores
    Components --> Session
    Components --> Platform
    Components --> AlbumArt
    JS -.->|"DotNetObjectReference / [JSInvokable]"| Components
    MainActivity --> BackCB --> Platform
    MainActivity --> Insets --> Platform
    Stores --> JSON
    AlbumArt --> ArtCache
    AlbumArt --> Lookups
    Stores -.->|"auto-fill / suggestion"| Lookups
    Lookups -->|"LoggingHttpMessageHandler"| Net
Loading

Platform-specific bits

Everything under src/KHost.Mobile/Platforms/<head>/ is the minimum native glue a Blazor Hybrid app needs; app logic never lives here.

Path Head Purpose
Platforms/Android/MainActivity.cs Android The single Activity (MauiAppCompatActivity). Wires InsetPublisher (edge-to-edge safe-area insets → ISafeAreaInsets), sets white status-bar icons, and installs OverlayBackPressedCallback (back button → IBackButtonService, plus the "press back again to exit" toast).
Platforms/Android/MainApplication.cs Android MauiApplication subclass; CreateMauiApp() just calls MauiProgram.CreateMauiApp().
Platforms/Android/AndroidLogcatLoggerProvider.cs Android Debug-only ILoggerProvider writing to logcat under the KHostCue tag — AddDebug() alone is silent on a debugger-less -t:Run deploy.
Platforms/Android/AndroidManifest.xml Android Permissions (location, camera for QR scan), app metadata.
Platforms/iOS/AppDelegate.cs, Program.cs iOS MauiUIApplicationDelegate subclass; same CreateMauiApp() bridge as Android.
Platforms/iOS/Info.plist, Resources/PrivacyInfo.xcprivacy iOS App metadata and Apple's required privacy-manifest declarations.
Platforms/MacCatalyst/AppDelegate.cs, Program.cs, Info.plist, Entitlements.plist Mac Catalyst Same delegate bridge; Catalyst-specific entitlements/plist for the dev-preview head.
Platforms/Windows/App.xaml(.cs), Package.appxmanifest, app.manifest Windows WinUI app shell + packaging manifest for the dev-iteration head.
src/KHost.Mobile/MainPage.xaml(.cs) All The one ContentPage hosting the BlazorWebView; also disables Android's native WebView overscroll stretch (OverScrollMode.Never) since CSS overscroll-behavior doesn't reach it.
src/KHost.Mobile/App.xaml.cs All CreateWindow sets the window title ("KHost Cue"); on Catalyst, PinToMobilePreviewViewport locks the window to the 393×852 mobile-preview size on first layout, then releases it back to resizable.

The QR scanner (IQrScanner) is conditionally compiled rather than platform-folder-only: MauiQrScanner (src/KHost.Mobile/Services/, Android/iOS, backed by the BarcodeScanning package — ML Kit / Apple Vision) vs. UnsupportedQrScanner (Infrastructure, Windows/Catalyst, a no-op returning IsSupported == false) are registered from MauiProgram.cs behind #if ANDROID || IOS, so the KaraFun sheet can resolve IQrScanner via DI on every head even where scanning isn't possible (the scan button itself is hidden there).

See also

  • Data storage — the JSON store pattern, file layout, atomic writes, per-singer namespacing.
  • UI components — the Razor component conventions, Sheet.razor, gesture JS modules.
  • External services — the KHost.Mobile.Clients lookups in detail (iTunes, Deezer, LRCLIB, GitHub, playlist import).
  • Building & testing — build commands per head, workload gotchas, test suites.
  • Conventions — code style, async/logging patterns, the store/client-backend/Blazor-component templates.

Clone this wiki locally