[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7D2H1ZKYWXNZPQTFMM6375C":3,"skill-same:01M7D2H1ZKYWXNZPQTFMM6375C":51},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":25,"commitSha":26,"skillDirectory":27,"forksCount":14,"repositoryHtmlUrl":28,"repositoryHomepageUrl":6,"ownerHtmlUrl":29,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":30,"install":31,"resources":44},"01M7D2H1ZKYWXNZPQTFMM6375C","maui-dependency-injection",null,"Guidance for configuring dependency injection in .NET MAUI apps — service registration in MauiProgram.cs, lifetime selection (Singleton \u002F Transient \u002F Scoped), constructor injection, Shell navigation auto-resolution, platform-specific registrations, and testability patterns. USE FOR: \"dependency injection\", \"DI setup\", \"AddSingleton\", \"AddTransient\", \"AddScoped\", \"service registration\", \"constructor injection\", \"IServiceProvider\", \"MauiProgram DI\", \"register services\", \"BindingContext injection\". DO NOT USE FOR: data binding (use maui-data-binding), Shell route configuration (use maui-shell-navigation), unit-test mocking frameworks (use standard xUnit and NSubstitute patterns).","itsmejay18\u002FAI-Skills-for-My-Development-Stack","itsmejay18","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F167779943?v=4","01M7CZRFC6DDZA5V2CX8WDSZED","Jay Jemino Ababon ","01M7CZRFCVRNW1SFHSQXEJ3CQN",0,"MIT","https:\u002F\u002Fgithub.com\u002Fitsmejay18\u002FAI-Skills-for-My-Development-Stack\u002Fblob\u002Fmain\u002F17-Software-Architecture\u002Fmaui-dependency-injection\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: maui-dependency-injection\ndescription: >\n  Guidance for configuring dependency injection in .NET MAUI apps — service\n  registration in MauiProgram.cs, lifetime selection (Singleton \u002F Transient \u002F Scoped),\n  constructor injection, Shell navigation auto-resolution, platform-specific\n  registrations, and testability patterns.\n  USE FOR: \"dependency injection\", \"DI setup\", \"AddSingleton\", \"AddTransient\",\n  \"AddScoped\", \"service registration\", \"constructor injection\", \"IServiceProvider\",\n  \"MauiProgram DI\", \"register services\", \"BindingContext injection\".\n  DO NOT USE FOR: data binding (use maui-data-binding), Shell route configuration\n  (use maui-shell-navigation), unit-test mocking frameworks (use standard xUnit\n  and NSubstitute patterns).\nlicense: MIT\n---\n\n# Dependency Injection in .NET MAUI\n\n.NET MAUI uses the same `Microsoft.Extensions.DependencyInjection` container as ASP.NET Core. All service registration happens in `MauiProgram.CreateMauiApp()` on `builder.Services`. The container is built once at startup and is immutable thereafter.\n\n## When to Use\n\n- Registering services, ViewModels, and Pages in `MauiProgram.cs`\n- Choosing between `AddSingleton`, `AddTransient`, and `AddScoped`\n- Wiring constructor injection for Pages and ViewModels\n- Leveraging Shell navigation to auto-resolve DI-registered Pages\n- Registering platform-specific service implementations with `#if` directives\n- Designing interfaces for testable service layers\n\n## When Not to Use\n\n- XAML data-binding syntax or compiled bindings — use the **maui-data-binding** skill\n- Shell route registration and query parameters — use the **maui-shell-navigation** skill\n- Mocking frameworks or test runners — use standard .NET testing tools (xUnit, NUnit, MSTest) and mocking libraries (NSubstitute, Moq)\n\n## Inputs\n\n- A .NET MAUI project with a `MauiProgram.cs` file\n- Knowledge of which services, ViewModels, and Pages need registration\n- Target platforms (Android, iOS, Mac Catalyst, Windows) for conditional registrations\n\n## Rules That Change the Answer\n\n| Situation | Do this | Why |\n|---|---|---|\n| Registering a Page or ViewModel | Prefer `AddTransient` | A fresh instance per navigation avoids stale state, and a Singleton page cannot be re-added to the visual tree after it is removed. Singleton is defensible for a genuinely single-instance page (e.g. a root tab you want to keep warm) |\n| Registering shared\u002Fexpensive state | `AddSingleton` | One instance app-wide (settings, DB connection, `HttpClient` handler) |\n| Tempted to use `AddScoped` | Use `AddTransient` (or `AddSingleton` if sharing is intended) | MAUI has **no** built-in request scope like ASP.NET Core's HTTP pipeline. MAUI does create one `IServiceScope` per window, so a Scoped service lives as long as that window — and resolved from the root provider it behaves like a Singleton. Neither gives you per-navigation freshness |\n| Navigating to a DI-registered page | Register the page **and** its ViewModel, then `Routing.RegisterRoute` | `Shell.Current.GoToAsync` resolves the page through DI and injects its constructor dependencies |\n| Platform-specific implementation | `#if` per platform **with every platform covered** | A missing platform branch leaves the service unregistered and throws at resolution time |\n\n**Do not** introduce DI into a project that isn't using it, swap a working service\nlifetime, or add an interface purely for symmetry — only when the user asked or it\nfixes a real defect.\n\n**Answer narrowly, but completely.** When you recommend a lifetime change, show the\nregistration code, and give the realistic alternatives rather than a single verdict —\nfor a unit-of-work or `DbContext` question that means `AddTransient`, an explicit\n`IServiceScopeFactory.CreateScope()`, **and** the factory pattern\n(`AddDbContextFactory`), with a note on when each fits. A one-line prescription is\nusually a worse answer than a short menu with trade-offs.\n\n```csharp\n\u002F\u002F Explicit scope when you genuinely need unit-of-work semantics\nusing var scope = scopeFactory.CreateScope();\nvar db = scope.ServiceProvider.GetRequiredService\u003CMyDbContext>();\n```\n\n## Workflow\n\n1. Identify all services, ViewModels, and Pages that need to participate in dependency injection.\n2. Choose the correct lifetime for each type — `AddSingleton` for shared services, `AddTransient` for Pages and ViewModels.\n3. Register all types in `MauiProgram.CreateMauiApp()` on `builder.Services`, grouping by category (services, HTTP, ViewModels, Pages).\n4. Register Pages as Shell routes in `AppShell.xaml.cs` so Shell navigation auto-resolves the full dependency graph.\n5. Wire each Page to its ViewModel via constructor injection, assigning the ViewModel as `BindingContext`.\n6. Add platform-specific registrations with `#if` directives, ensuring every target platform is covered or has a fallback.\n7. Verify resolution works by running the app and confirming no `null` dependencies or missing-registration exceptions at runtime.\n\n---\n\n## Lifetime Selection\n\n| Lifetime | When to Use | Typical Types |\n|---|---|---|\n| `AddSingleton\u003CT>()` | Shared state, expensive to create, app-wide config | `HttpClient` factory, settings service, database connection |\n| `AddTransient\u003CT>()` | Lightweight, stateless, or needs a fresh instance per use | Pages, ViewModels, per-call API wrappers |\n| `AddScoped\u003CT>()` | Per-window lifetime, or a manually created `IServiceScope` | Scoped unit-of-work (rare in MAUI) |\n\n**Key rule:** Register Pages and ViewModels as **Transient** by default. Register shared services as **Singleton**.\n\n> ⚠️ **Avoid `AddScoped` unless you manually manage `IServiceScope`.** MAUI has no built-in request scope like ASP.NET Core. MAUI creates one `IServiceScope` per window, so a Scoped service lives as long as that window; resolved from the root provider it silently behaves as a Singleton. Neither gives per-navigation freshness.\n\n---\n\n## Registration Pattern in MauiProgram.cs\n\n```csharp\npublic static MauiApp CreateMauiApp()\n{\n    var builder = MauiApp.CreateBuilder();\n    builder.UseMauiApp\u003CApp>();\n\n    \u002F\u002F Services — Singleton for shared state\n    builder.Services.AddSingleton\u003CIDataService, DataService>();\n    builder.Services.AddSingleton\u003CISettingsService, SettingsService>();\n\n    \u002F\u002F HTTP — use typed or named clients via IHttpClientFactory\n    \u002F\u002F Requires NuGet: Microsoft.Extensions.Http\n    builder.Services.AddHttpClient\u003CIApiClient, ApiClient>();\n\n    \u002F\u002F ViewModels — Transient for fresh state per navigation\n    builder.Services.AddTransient\u003CMainViewModel>();\n    builder.Services.AddTransient\u003CDetailViewModel>();\n\n    \u002F\u002F Pages — Transient so constructor injection fires each time\n    builder.Services.AddTransient\u003CMainPage>();\n    builder.Services.AddTransient\u003CDetailPage>();\n\n    return builder.Build();\n}\n```\n\n---\n\n## Constructor Injection\n\nInject dependencies through constructor parameters. The container resolves them automatically when the type is itself resolved from DI.\n\n```csharp\npublic class MainViewModel\n{\n    private readonly IDataService _dataService;\n\n    public MainViewModel(IDataService dataService)\n    {\n        _dataService = dataService;\n    }\n\n    public async Task LoadAsync() => Items = await _dataService.GetItemsAsync();\n}\n```\n\n### ViewModel → Page Wiring\n\nRegister both Page and ViewModel. Inject the ViewModel into the Page and assign it as `BindingContext`:\n\n```csharp\npublic partial class MainPage : ContentPage\n{\n    public MainPage(MainViewModel viewModel)\n    {\n        InitializeComponent();\n        BindingContext = viewModel;\n    }\n}\n```\n\n---\n\n## Shell Navigation Auto-Resolution\n\nWhen a Page is registered in DI **and** as a Shell route, Shell resolves it (and its full dependency graph) automatically on navigation:\n\n```csharp\n\u002F\u002F MauiProgram.cs\nbuilder.Services.AddTransient\u003CDetailPage>();\nbuilder.Services.AddTransient\u003CDetailViewModel>();\n\n\u002F\u002F AppShell.xaml.cs\nRouting.RegisterRoute(nameof(DetailPage), typeof(DetailPage));\n\n\u002F\u002F Navigate — DI resolves DetailPage + DetailViewModel\nawait Shell.Current.GoToAsync(nameof(DetailPage));\n```\n\n### Passing parameters to a DI-resolved ViewModel\n\nDI supplies the ViewModel's *dependencies*; navigation parameters arrive separately.\nDon't try to inject them through the constructor — implement `IQueryAttributable`\non the ViewModel so it receives both:\n\n```csharp\npublic class DetailViewModel : ObservableObject, IQueryAttributable\n{\n    readonly IDataService _data;   \u002F\u002F ← injected by DI\n\n    public DetailViewModel(IDataService data) => _data = data;\n\n    public void ApplyQueryAttributes(IDictionary\u003Cstring, object> query)\n    {\n        \u002F\u002F ← supplied by navigation\n        if (query.TryGetValue(\"id\", out var id))\n            LoadAsync(id.ToString()!);\n    }\n}\n\n\u002F\u002F Navigate with a parameter — the page and its ViewModel still come from DI\nawait Shell.Current.GoToAsync($\"{nameof(DetailPage)}?id={product.Id}\");\n```\n\nShell applies query attributes to the page **and** its `BindingContext`, so the\nViewModel receives them without any wiring in the page.\n\n---\n\n## Platform-Specific Registration\n\nUse preprocessor directives to register platform implementations. Always cover every target platform or provide a no-op fallback to avoid runtime `null`.\n\n```csharp\n#if ANDROID\nbuilder.Services.AddSingleton\u003CINotificationService, AndroidNotificationService>();\n#elif IOS || MACCATALYST\nbuilder.Services.AddSingleton\u003CINotificationService, AppleNotificationService>();\n#elif WINDOWS\nbuilder.Services.AddSingleton\u003CINotificationService, WindowsNotificationService>();\n#else\nbuilder.Services.AddSingleton\u003CINotificationService, NoOpNotificationService>();\n#endif\n```\n\n---\n\n## Explicit Resolution (Last Resort)\n\nPrefer constructor injection. Use explicit resolution only where injection is genuinely unavailable (custom handlers, platform callbacks):\n\n```csharp\n\u002F\u002F From any Element with a Handler\nvar service = this.Handler.MauiContext.Services.GetService\u003CIDataService>();\n```\n\nFor dynamic resolution, inject `IServiceProvider`:\n\n```csharp\npublic class NavigationService(IServiceProvider serviceProvider)\n{\n    public T ResolvePage\u003CT>() where T : Page\n        => serviceProvider.GetRequiredService\u003CT>();\n}\n```\n\n---\n\n## Interface-First Pattern for Testability\n\nDefine interfaces for every service so implementations can be swapped in tests:\n\n```csharp\npublic interface IDataService\n{\n    Task\u003CList\u003CItem>> GetItemsAsync();\n}\n\n\u002F\u002F Production registration\nbuilder.Services.AddSingleton\u003CIDataService, DataService>();\n\n\u002F\u002F Test registration — swap without touching production code\nvar services = new ServiceCollection();\nservices.AddSingleton\u003CIDataService, FakeDataService>();\n```\n\n---\n\n## Common Pitfalls\n\n### 1. Singleton ViewModels Cause Stale Data\n\n```csharp\n\u002F\u002F ❌ ViewModel keeps stale state across navigations\nbuilder.Services.AddSingleton\u003CDetailViewModel>();\n\n\u002F\u002F ✅ Fresh instance each navigation\nbuilder.Services.AddTransient\u003CDetailViewModel>();\n```\n\n### 2. ContentTemplate Pages Are Not Created Through DI\n\nPages declared in Shell XAML via `\u003CShellContent ContentTemplate=\"{DataTemplate views:DetailPage}\">` are instantiated with `Activator.CreateInstance` (`ElementTemplate.cs`), **not** through the service provider. Constructor injection does not run on that path: if the page's only constructor takes dependencies, you get a `MissingMethodException` — not a silently `null` dependency.\n\nPages reached through `Routing.RegisterRoute` + `GoToAsync` are different: they go through `ActivatorUtilities.GetServiceOrCreateInstance` (`Routing.cs`), which injects registered dependencies even if the page type itself was never registered, and **throws** if a required dependency cannot be resolved.\n\n```csharp\n\u002F\u002F Registering the page and its dependencies keeps both paths working\nbuilder.Services.AddTransient\u003CDetailPage>();\nbuilder.Services.AddTransient\u003CDetailViewModel>();\n```\n\nIf you need DI for a tab\u002Fflyout page, give it a parameterless constructor that resolves what it needs, or navigate to it by route instead of embedding it in `ContentTemplate`.\n\n### 3. XAML Resource Parsing vs. DI Timing\n\nXAML resources in `App.xaml` are parsed during `InitializeComponent()` — before the container is fully available. Defer service-dependent work to `CreateWindow()`:\n\n```csharp\npublic partial class App : Application\n{\n    private readonly IServiceProvider _services;\n\n    public App(IServiceProvider services)\n    {\n        _services = services;\n        InitializeComponent();\n    }\n\n    protected override Window CreateWindow(IActivationState? activationState)\n    {\n        \u002F\u002F Safe — container is fully built\n        \u002F\u002F Requires: builder.Services.AddTransient\u003CAppShell>() in MauiProgram.cs\n        var appShell = _services.GetRequiredService\u003CAppShell>();\n        return new Window(appShell);\n    }\n}\n```\n\n### 4. Service Locator Anti-Pattern\n\n```csharp\n\u002F\u002F ❌ Hides dependencies, hard to test\nvar svc = this.Handler.MauiContext.Services.GetService\u003CIDataService>();\n\n\u002F\u002F ✅ Constructor injection — explicit and testable\npublic class MyViewModel(IDataService dataService) { }\n```\n\n### 5. Missing Platform in Conditional Registration\n\nForgetting a platform in `#if` blocks means `GetService\u003CT>()` returns `null` at runtime on that platform. Always include an `#else` fallback or cover every target.\n\n### 6. AddScoped Without Manual Scope\n\nSee the rule table above: `AddScoped` gives you either window lifetime or Singleton behaviour, never per-navigation freshness. Use `AddTransient` or `AddSingleton` unless you explicitly create and manage an `IServiceScope`.\n\n---\n\n## Checklist\n\n- [ ] Every Page and ViewModel that needs injection is registered in `MauiProgram.cs`\n- [ ] Pages and ViewModels use `AddTransient`; shared services use `AddSingleton`\n- [ ] Constructor injection used everywhere possible; service locator only as last resort\n- [ ] Interfaces defined for services that need test substitution\n- [ ] Platform-specific `#if` registrations cover all target platforms or include a fallback\n- [ ] Service-dependent work deferred to `CreateWindow()`, not run during XAML parse\n- [ ] `AddScoped` used only when window lifetime is intended, or alongside a manually created `IServiceScope`\n\n## References\n\n- [Dependency injection in .NET MAUI](https:\u002F\u002Flearn.microsoft.com\u002Fdotnet\u002Fmaui\u002Ffundamentals\u002Fdependency-injection)\n- [.NET dependency injection fundamentals](https:\u002F\u002Flearn.microsoft.com\u002Fdotnet\u002Fcore\u002Fextensions\u002Fdependency-injection)\n","# Dependency Injection in .NET MAUI\n\n.NET MAUI uses the same `Microsoft.Extensions.DependencyInjection` container as ASP.NET Core. All service registration happens in `MauiProgram.CreateMauiApp()` on `builder.Services`. The container is built once at startup and is immutable thereafter.\n\n## When to Use\n\n- Registering services, ViewModels, and Pages in `MauiProgram.cs`\n- Choosing between `AddSingleton`, `AddTransient`, and `AddScoped`\n- Wiring constructor injection for Pages and ViewModels\n- Leveraging Shell navigation to auto-resolve DI-registered Pages\n- Registering platform-specific service implementations with `#if` directives\n- Designing interfaces for testable service layers\n\n## When Not to Use\n\n- XAML data-binding syntax or compiled bindings — use the **maui-data-binding** skill\n- Shell route registration and query parameters — use the **maui-shell-navigation** skill\n- Mocking frameworks or test runners — use standard .NET testing tools (xUnit, NUnit, MSTest) and mocking libraries (NSubstitute, Moq)\n\n## Inputs\n\n- A .NET MAUI project with a `MauiProgram.cs` file\n- Knowledge of which services, ViewModels, and Pages need registration\n- Target platforms (Android, iOS, Mac Catalyst, Windows) for conditional registrations\n\n## Rules That Change the Answer\n\n| Situation | Do this | Why |\n|---|---|---|\n| Registering a Page or ViewModel | Prefer `AddTransient` | A fresh instance per navigation avoids stale state, and a Singleton page cannot be re-added to the visual tree after it is removed. Singleton is defensible for a genuinely single-instance page (e.g. a root tab you want to keep warm) |\n| Registering shared\u002Fexpensive state | `AddSingleton` | One instance app-wide (settings, DB connection, `HttpClient` handler) |\n| Tempted to use `AddScoped` | Use `AddTransient` (or `AddSingleton` if sharing is intended) | MAUI has **no** built-in request scope like ASP.NET Core's HTTP pipeline. MAUI does create one `IServiceScope` per window, so a Scoped service lives as long as that window — and resolved from the root provider it behaves like a Singleton. Neither gives you per-navigation freshness |\n| Navigating to a DI-registered page | Register the page **and** its ViewModel, then `Routing.RegisterRoute` | `Shell.Current.GoToAsync` resolves the page through DI and injects its constructor dependencies |\n| Platform-specific implementation | `#if` per platform **with every platform covered** | A missing platform branch leaves the service unregistered and throws at resolution time |\n\n**Do not** introduce DI into a project that isn't using it, swap a working service\nlifetime, or add an interface purely for symmetry — only when the user asked or it\nfixes a real defect.\n\n**Answer narrowly, but completely.** When you recommend a lifetime change, show the\nregistration code, and give the realistic alternatives rather than a single verdict —\nfor a unit-of-work or `DbContext` question that means `AddTransient`, an explicit\n`IServiceScopeFactory.CreateScope()`, **and** the factory pattern\n(`AddDbContextFactory`), with a note on when each fits. A one-line prescription is\nusually a worse answer than a short menu with trade-offs.\n\n```csharp\n\u002F\u002F Explicit scope when you genuinely need unit-of-work semantics\nusing var scope = scopeFactory.CreateScope();\nvar db = scope.ServiceProvider.GetRequiredService\u003CMyDbContext>();\n```\n\n## Workflow\n\n1. Identify all services, ViewModels, and Pages that need to participate in dependency injection.\n2. Choose the correct lifetime for each type — `AddSingleton` for shared services, `AddTransient` for Pages and ViewModels.\n3. Register all types in `MauiProgram.CreateMauiApp()` on `builder.Services`, grouping by category (services, HTTP, ViewModels, Pages).\n4. Register Pages as Shell routes in `AppShell.xaml.cs` so Shell navigation auto-resolves the full dependency graph.\n5. Wire each Page to its ViewModel via constructor injection, assigning the ViewModel as `BindingContext`.\n6. Add platform-specific registrations with `#if` directives, ensuring every target platform is covered or has a fallback.\n7. Verify resolution works by running the app and confirming no `null` dependencies or missing-registration exceptions at runtime.\n\n---\n\n## Lifetime Selection\n\n| Lifetime | When to Use | Typical Types |\n|---|---|---|\n| `AddSingleton\u003CT>()` | Shared state, expensive to create, app-wide config | `HttpClient` factory, settings service, database connection |\n| `AddTransient\u003CT>()` | Lightweight, stateless, or needs a fresh instance per use | Pages, ViewModels, per-call API wrappers |\n| `AddScoped\u003CT>()` | Per-window lifetime, or a manually created `IServiceScope` | Scoped unit-of-work (rare in MAUI) |\n\n**Key rule:** Register Pages and ViewModels as **Transient** by default. Register shared services as **Singleton**.\n\n> ⚠️ **Avoid `AddScoped` unless you manually manage `IServiceScope`.** MAUI has no built-in request scope like ASP.NET Core. MAUI creates one `IServiceScope` per window, so a Scoped service lives as long as that window; resolved from the root provider it silently behaves as a Singleton. Neither gives per-navigation freshness.\n\n---\n\n## Registration Pattern in MauiProgram.cs\n\n```csharp\npublic static MauiApp CreateMauiApp()\n{\n    var builder = MauiApp.CreateBuilder();\n    builder.UseMauiApp\u003CApp>();\n\n    \u002F\u002F Services — Singleton for shared state\n    builder.Services.AddSingleton\u003CIDataService, DataService>();\n    builder.Services.AddSingleton\u003CISettingsService, SettingsService>();\n\n    \u002F\u002F HTTP — use typed or named clients via IHttpClientFactory\n    \u002F\u002F Requires NuGet: Microsoft.Extensions.Http\n    builder.Services.AddHttpClient\u003CIApiClient, ApiClient>();\n\n    \u002F\u002F ViewModels — Transient for fresh state per navigation\n    builder.Services.AddTransient\u003CMainViewModel>();\n    builder.Services.AddTransient\u003CDetailViewModel>();\n\n    \u002F\u002F Pages — Transient so constructor injection fires each time\n    builder.Services.AddTransient\u003CMainPage>();\n    builder.Services.AddTransient\u003CDetailPage>();\n\n    return builder.Build();\n}\n```\n\n---\n\n## Constructor Injection\n\nInject dependencies through constructor parameters. The container resolves them automatically when the type is itself resolved from DI.\n\n```csharp\npublic class MainViewModel\n{\n    private readonly IDataService _dataService;\n\n    public MainViewModel(IDataService dataService)\n    {\n        _dataService = dataService;\n    }\n\n    public async Task LoadAsync() => Items = await _dataService.GetItemsAsync();\n}\n```\n\n### ViewModel → Page Wiring\n\nRegister both Page and ViewModel. Inject the ViewModel into the Page and assign it as `BindingContext`:\n\n```csharp\npublic partial class MainPage : ContentPage\n{\n    public MainPage(MainViewModel viewModel)\n    {\n        InitializeComponent();\n        BindingContext = viewModel;\n    }\n}\n```\n\n---\n\n## Shell Navigation Auto-Resolution\n\nWhen a Page is registered in DI **and** as a Shell route, Shell resolves it (and its full dependency graph) automatically on navigation:\n\n```csharp\n\u002F\u002F MauiProgram.cs\nbuilder.Services.AddTransient\u003CDetailPage>();\nbuilder.Services.AddTransient\u003CDetailViewModel>();\n\n\u002F\u002F AppShell.xaml.cs\nRouting.RegisterRoute(nameof(DetailPage), typeof(DetailPage));\n\n\u002F\u002F Navigate — DI resolves DetailPage + DetailViewModel\nawait Shell.Current.GoToAsync(nameof(DetailPage));\n```\n\n### Passing parameters to a DI-resolved ViewModel\n\nDI supplies the ViewModel's *dependencies*; navigation parameters arrive separately.\nDon't try to inject them through the constructor — implement `IQueryAttributable`\non the ViewModel so it receives both:\n\n```csharp\npublic class DetailViewModel : ObservableObject, IQueryAttributable\n{\n    readonly IDataService _data;   \u002F\u002F ← injected by DI\n\n    public DetailViewModel(IDataService data) => _data = data;\n\n    public void ApplyQueryAttributes(IDictionary\u003Cstring, object> query)\n    {\n        \u002F\u002F ← supplied by navigation\n        if (query.TryGetValue(\"id\", out var id))\n            LoadAsync(id.ToString()!);\n    }\n}\n\n\u002F\u002F Navigate with a parameter — the page and its ViewModel still come from DI\nawait Shell.Current.GoToAsync($\"{nameof(DetailPage)}?id={product.Id}\");\n```\n\nShell applies query attributes to the page **and** its `BindingContext`, so the\nViewModel receives them without any wiring in the page.\n\n---\n\n## Platform-Specific Registration\n\nUse preprocessor directives to register platform implementations. Always cover every target platform or provide a no-op fallback to avoid runtime `null`.\n\n```csharp\n#if ANDROID\nbuilder.Services.AddSingleton\u003CINotificationService, AndroidNotificationService>();\n#elif IOS || MACCATALYST\nbuilder.Services.AddSingleton\u003CINotificationService, AppleNotificationService>();\n#elif WINDOWS\nbuilder.Services.AddSingleton\u003CINotificationService, WindowsNotificationService>();\n#else\nbuilder.Services.AddSingleton\u003CINotificationService, NoOpNotificationService>();\n#endif\n```\n\n---\n\n## Explicit Resolution (Last Resort)\n\nPrefer constructor injection. Use explicit resolution only where injection is genuinely unavailable (custom handlers, platform callbacks):\n\n```csharp\n\u002F\u002F From any Element with a Handler\nvar service = this.Handler.MauiContext.Services.GetService\u003CIDataService>();\n```\n\nFor dynamic resolution, inject `IServiceProvider`:\n\n```csharp\npublic class NavigationService(IServiceProvider serviceProvider)\n{\n    public T ResolvePage\u003CT>() where T : Page\n        => serviceProvider.GetRequiredService\u003CT>();\n}\n```\n\n---\n\n## Interface-First Pattern for Testability\n\nDefine interfaces for every service so implementations can be swapped in tests:\n\n```csharp\npublic interface IDataService\n{\n    Task\u003CList\u003CItem>> GetItemsAsync();\n}\n\n\u002F\u002F Production registration\nbuilder.Services.AddSingleton\u003CIDataService, DataService>();\n\n\u002F\u002F Test registration — swap without touching production code\nvar services = new ServiceCollection();\nservices.AddSingleton\u003CIDataService, FakeDataService>();\n```\n\n---\n\n## Common Pitfalls\n\n### 1. Singleton ViewModels Cause Stale Data\n\n```csharp\n\u002F\u002F ❌ ViewModel keeps stale state across navigations\nbuilder.Services.AddSingleton\u003CDetailViewModel>();\n\n\u002F\u002F ✅ Fresh instance each navigation\nbuilder.Services.AddTransient\u003CDetailViewModel>();\n```\n\n### 2. ContentTemplate Pages Are Not Created Through DI\n\nPages declared in Shell XAML via `\u003CShellContent ContentTemplate=\"{DataTemplate views:DetailPage}\">` are instantiated with `Activator.CreateInstance` (`ElementTemplate.cs`), **not** through the service provider. Constructor injection does not run on that path: if the page's only constructor takes dependencies, you get a `MissingMethodException` — not a silently `null` dependency.\n\nPages reached through `Routing.RegisterRoute` + `GoToAsync` are different: they go through `ActivatorUtilities.GetServiceOrCreateInstance` (`Routing.cs`), which injects registered dependencies even if the page type itself was never registered, and **throws** if a required dependency cannot be resolved.\n\n```csharp\n\u002F\u002F Registering the page and its dependencies keeps both paths working\nbuilder.Services.AddTransient\u003CDetailPage>();\nbuilder.Services.AddTransient\u003CDetailViewModel>();\n```\n\nIf you need DI for a tab\u002Fflyout page, give it a parameterless constructor that resolves what it needs, or navigate to it by route instead of embedding it in `ContentTemplate`.\n\n### 3. XAML Resource Parsing vs. DI Timing\n\nXAML resources in `App.xaml` are parsed during `InitializeComponent()` — before the container is fully available. Defer service-dependent work to `CreateWindow()`:\n\n```csharp\npublic partial class App : Application\n{\n    private readonly IServiceProvider _services;\n\n    public App(IServiceProvider services)\n    {\n        _services = services;\n        InitializeComponent();\n    }\n\n    protected override Window CreateWindow(IActivationState? activationState)\n    {\n        \u002F\u002F Safe — container is fully built\n        \u002F\u002F Requires: builder.Services.AddTransient\u003CAppShell>() in MauiProgram.cs\n        var appShell = _services.GetRequiredService\u003CAppShell>();\n        return new Window(appShell);\n    }\n}\n```\n\n### 4. Service Locator Anti-Pattern\n\n```csharp\n\u002F\u002F ❌ Hides dependencies, hard to test\nvar svc = this.Handler.MauiContext.Services.GetService\u003CIDataService>();\n\n\u002F\u002F ✅ Constructor injection — explicit and testable\npublic class MyViewModel(IDataService dataService) { }\n```\n\n### 5. Missing Platform in Conditional Registration\n\nForgetting a platform in `#if` blocks means `GetService\u003CT>()` returns `null` at runtime on that platform. Always include an `#else` fallback or cover every target.\n\n### 6. AddScoped Without Manual Scope\n\nSee the rule table above: `AddScoped` gives you either window lifetime or Singleton behaviour, never per-navigation freshness. Use `AddTransient` or `AddSingleton` unless you explicitly create and manage an `IServiceScope`.\n\n---\n\n## Checklist\n\n- [ ] Every Page and ViewModel that needs injection is registered in `MauiProgram.cs`\n- [ ] Pages and ViewModels use `AddTransient`; shared services use `AddSingleton`\n- [ ] Constructor injection used everywhere possible; service locator only as last resort\n- [ ] Interfaces defined for services that need test substitution\n- [ ] Platform-specific `#if` registrations cover all target platforms or include a fallback\n- [ ] Service-dependent work deferred to `CreateWindow()`, not run during XAML parse\n- [ ] `AddScoped` used only when window lifetime is intended, or alongside a manually created `IServiceScope`\n\n## References\n\n- [Dependency injection in .NET MAUI](https:\u002F\u002Flearn.microsoft.com\u002Fdotnet\u002Fmaui\u002Ffundamentals\u002Fdependency-injection)\n- [.NET dependency injection fundamentals](https:\u002F\u002Flearn.microsoft.com\u002Fdotnet\u002Fcore\u002Fextensions\u002Fdependency-injection)\n",{"name":5,"license":15,"description":24},"Guidance for configuring dependency injection in .NET MAUI apps — service registration in MauiProgram.cs, lifetime selection (Singleton \u002F Transient \u002F Scoped), constructor injection, Shell navigation auto-resolution, platform-specific registrations, and testability patterns. USE FOR: \"dependency injection\", \"DI setup\", \"AddSingleton\", \"AddTransient\", \"AddScoped\", \"service registration\", \"constructor injection\", \"IServiceProvider\", \"MauiProgram DI\", \"register services\", \"BindingContext injection\". DO NOT USE FOR: data binding (use maui-data-binding), Shell route configuration (use maui-shell-navigation), unit-test mocking frameworks (use standard xUnit and NSubstitute patterns).\n","main","30954af1dcd1a74b63f05deb2e2c41e5ecae4a82","17-Software-Architecture\u002Fmaui-dependency-injection","https:\u002F\u002Fgithub.com\u002Fitsmejay18\u002FAI-Skills-for-My-Development-Stack","https:\u002F\u002Fgithub.com\u002Fitsmejay18","2026-09-18 16:06:36",{"source":8,"skillName":5,"commands":32,"prompt":42,"zipAvailable":43},[33,36,39],{"tool":34,"command":35},"npx","npx skills add itsmejay18\u002FAI-Skills-for-My-Development-Stack --skill maui-dependency-injection",{"tool":37,"command":38},"bunx","bunx skills add itsmejay18\u002FAI-Skills-for-My-Development-Stack --skill maui-dependency-injection",{"tool":40,"command":41},"pnpm","pnpm dlx skills add itsmejay18\u002FAI-Skills-for-My-Development-Stack --skill maui-dependency-injection","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fitsmejay18\u002FAI-Skills-for-My-Development-Stack\u002Fblob\u002Fmain\u002F17-Software-Architecture\u002Fmaui-dependency-injection\u002FSKILL.md",true,[45],{"path":46,"resourceType":47,"resourceTypeDesc":48,"sizeBytes":49,"sourceHtmlUrl":50},"references\u002Fdependency-injection-api.md","REFERENCE","参考文档",4236,"https:\u002F\u002Fgithub.com\u002Fitsmejay18\u002FAI-Skills-for-My-Development-Stack\u002Fblob\u002Fmain\u002F17-Software-Architecture\u002Fmaui-dependency-injection\u002Freferences\u002Fdependency-injection-api.md",[52,59,66,73,80,87],{"skillNo":53,"name":54,"nameZh":6,"description":55,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":56,"categories":57,"keywords":58,"publishedAt":19},"01M7D2RKBHPZ3E1RNN5DWHT550","vectorization","Design, implement, optimize, and review SIMD code in .NET. USE FOR: vectorizing scalar loops with TensorPrimitives, Vector64\u002F128\u002F256\u002F512, or platform hardware intrinsics; reviewing existing SIMD code, including Vector\u003CT>, for contract equivalence, tail handling, memory safety, portability, fallbacks, and measured performance. DO NOT USE FOR: performance work unrelated to SIMD or vectorization.","https:\u002F\u002Fgithub.com\u002Fitsmejay18\u002FAI-Skills-for-My-Development-Stack\u002Fblob\u002Fmain\u002F20-Performance-Optimization\u002Fvectorization\u002FSKILL.md",[],[],{"skillNo":60,"name":61,"nameZh":6,"description":62,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":63,"categories":64,"keywords":65,"publishedAt":19},"01M7D2RDJ7RN3QK8GJR0QTER1D","resolve-project-references","Guide for interpreting ResolveProjectReferences time in MSBuild performance summaries. Activate when ResolveProjectReferences appears as the most expensive target and developers are trying to optimize it directly. Explains that the reported time includes wait time for dependent project builds and is misleading. Guides users to focus on task self-time instead. Do not activate for general build performance -- use build-perf-diagnostics instead.","https:\u002F\u002Fgithub.com\u002Fitsmejay18\u002FAI-Skills-for-My-Development-Stack\u002Fblob\u002Fmain\u002F20-Performance-Optimization\u002Fresolve-project-references\u002FSKILL.md",[],[],{"skillNo":67,"name":68,"nameZh":6,"description":69,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":70,"categories":71,"keywords":72,"publishedAt":19},"01M7D2R1H2GTNZYHG9YRX3JDQW","optimizing-ef-core-queries","Optimize and improve the performance of slow Entity Framework Core (EF Core) queries: make them generate less SQL, make fewer database round-trips, and return results faster. Use whenever an EF Core or DbContext query or data-access path is slow or should be made faster — whether or not EF Core owns the database schema. For EF Core, not Dapper or raw ADO.NET.","https:\u002F\u002Fgithub.com\u002Fitsmejay18\u002FAI-Skills-for-My-Development-Stack\u002Fblob\u002Fmain\u002F20-Performance-Optimization\u002Foptimizing-ef-core-queries\u002FSKILL.md",[],[],{"skillNo":74,"name":75,"nameZh":6,"description":76,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":77,"categories":78,"keywords":79,"publishedAt":19},"01M7D2QREG04W1YT0NEBHEW5C9","microbenchmarking","Activate this skill when BenchmarkDotNet (BDN) is involved in the task — creating, running, configuring, or reviewing BDN benchmarks. Also activate when microbenchmarking .NET code would be useful and BenchmarkDotNet is the likely tool. Consider activating when answering a .NET performance question requires measurement and BenchmarkDotNet may be needed. Covers microbenchmark design, BDN configuration and project setup, how to run BDN microbenchmarks efficiently and effectively, and using BDN for side-by-side performance comparisons. Do NOT use for profiling\u002Ftracing .NET code (dotnet-trace, PerfView), production telemetry, or load\u002Fstress testing (Crank, k6).","https:\u002F\u002Fgithub.com\u002Fitsmejay18\u002FAI-Skills-for-My-Development-Stack\u002Fblob\u002Fmain\u002F20-Performance-Optimization\u002Fmicrobenchmarking\u002FSKILL.md",[],[],{"skillNo":81,"name":82,"nameZh":6,"description":83,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":84,"categories":85,"keywords":86,"publishedAt":19},"01M7D2QGE175XWPZVACVH2868Z","incremental-build","Guide for optimizing MSBuild incremental builds. USE FOR: builds slower than expected on subsequent runs, 'nothing changed but it rebuilds anyway', diagnosing why targets re-execute unnecessarily, fixing broken no-op builds. Covers 8 common causes: missing Inputs\u002FOutputs on custom targets, volatile properties in output paths (timestamps\u002FGUIDs), file writes outside tracked Outputs, missing FileWrites registration, glob changes, Visual Studio Fast Up-to-Date Check (FUTDC) issues. Key diagnostic: look for 'Building target completely' vs 'Skipping target' in binlog. DO NOT USE FOR: first-time build slowness (use build-perf-baseline), parallelism issues (use build-parallelism), evaluation-phase slowness (use eval-performance), non-MSBuild build systems.","https:\u002F\u002Fgithub.com\u002Fitsmejay18\u002FAI-Skills-for-My-Development-Stack\u002Fblob\u002Fmain\u002F20-Performance-Optimization\u002Fincremental-build\u002FSKILL.md",[],[],{"skillNo":88,"name":89,"nameZh":6,"description":90,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":91,"categories":92,"keywords":93,"publishedAt":19},"01M7D2Q1DQTC6K49R73WQTTPSB","eval-performance","Guide for diagnosing and improving MSBuild project evaluation performance. USE FOR: builds slow before any compilation starts, high evaluation time in binlog analysis, expensive glob patterns walking large directories (node_modules, .git, bin\u002Fobj), deep import chains (>20 levels), preprocessed output >10K lines indicating heavy evaluation, property functions with file I\u002FO ($([System.IO.File]::ReadAllText(...))), multiple evaluations per project. Covers the 5 MSBuild evaluation phases, glob optimization via DefaultItemExcludes, import chain analysis with \u002Fpp preprocessing. DO NOT USE FOR: compilation-time slowness (use build-perf-diagnostics), incremental build issues (use incremental-build), non-MSBuild build systems.","https:\u002F\u002Fgithub.com\u002Fitsmejay18\u002FAI-Skills-for-My-Development-Stack\u002Fblob\u002Fmain\u002F20-Performance-Optimization\u002Feval-performance\u002FSKILL.md",[],[]]