[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7CVAMRRWB95WMHBK3XESPZV":3,"skill-same:01M7CVAMRRWB95WMHBK3XESPZV":52},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":18,"linkOnly":19,"markdownContent":20,"markdownBody":21,"frontMatter":22,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":13,"repositoryHtmlUrl":27,"repositoryHomepageUrl":6,"ownerHtmlUrl":28,"ownerBlogUrl":29,"ownerDescription":30,"updatedAt":31,"install":32,"resources":45},"01M7CVAMRRWB95WMHBK3XESPZV","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).","deadmade\u002Fdead-agent-skills","deadmade","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F130925709?v=4","01M7CTQ65AGYR4J9K9TX0YR9V3","01M7CTQ66B4VMJFEDZP4EKKE6K",0,"MIT","https:\u002F\u002Fgithub.com\u002Fdeadmade\u002Fdead-agent-skills\u002Fblob\u002Fmain\u002Fplugins\u002Fopt-in\u002Fimplementation\u002Fcsharp-skills\u002Flibrary\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":14,"description":23},"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","ccab8dffc0ecc173838f51e4c5f0d3b51a704f41","plugins\u002Fopt-in\u002Fimplementation\u002Fcsharp-skills\u002Flibrary\u002Fmaui-dependency-injection","https:\u002F\u002Fgithub.com\u002Fdeadmade\u002Fdead-agent-skills","https:\u002F\u002Fgithub.com\u002Fdeadmade","https:\u002F\u002Fdeadmade.github.io\u002F","Blood, an Ocean of blood","2026-11-14 02:03:31",{"source":8,"skillName":5,"commands":33,"prompt":43,"zipAvailable":44},[34,37,40],{"tool":35,"command":36},"npx","npx skills add deadmade\u002Fdead-agent-skills --skill maui-dependency-injection",{"tool":38,"command":39},"bunx","bunx skills add deadmade\u002Fdead-agent-skills --skill maui-dependency-injection",{"tool":41,"command":42},"pnpm","pnpm dlx skills add deadmade\u002Fdead-agent-skills --skill maui-dependency-injection","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fdeadmade\u002Fdead-agent-skills\u002Fblob\u002Fmain\u002Fplugins\u002Fopt-in\u002Fimplementation\u002Fcsharp-skills\u002Flibrary\u002Fmaui-dependency-injection\u002FSKILL.md",true,[46],{"path":47,"resourceType":48,"resourceTypeDesc":49,"sizeBytes":50,"sourceHtmlUrl":51},"references\u002Fdependency-injection-api.md","REFERENCE","参考文档",4236,"https:\u002F\u002Fgithub.com\u002Fdeadmade\u002Fdead-agent-skills\u002Fblob\u002Fmain\u002Fplugins\u002Fopt-in\u002Fimplementation\u002Fcsharp-skills\u002Flibrary\u002Fmaui-dependency-injection\u002Freferences\u002Fdependency-injection-api.md",[53,60,69,77,84,91],{"skillNo":54,"name":55,"nameZh":6,"description":56,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":57,"categories":58,"keywords":59,"publishedAt":18},"01M7CVRBFTXSTTQ7F5P6PJEFYA","rust-best-practices","Guide for writing idiomatic Rust code based on Apollo GraphQL's best practices handbook. Use this skill when: (1) writing new Rust code or functions, (2) reviewing or refactoring existing Rust code, (3) deciding between borrowing vs cloning or ownership patterns, (4) implementing error handling with Result types, (5) optimizing Rust code for performance, (6) writing tests or documentation for Rust projects.","https:\u002F\u002Fgithub.com\u002Fdeadmade\u002Fdead-agent-skills\u002Fblob\u002Fmain\u002Fplugins\u002Fopt-in\u002Fimplementation\u002Frust-skills\u002Fskills\u002Frust-best-practices\u002FSKILL.md",[],[],{"skillNo":61,"name":62,"nameZh":6,"description":63,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":64,"licenseFileUrl":65,"sourceHtmlUrl":66,"categories":67,"keywords":68,"publishedAt":18},"01M7CVR0W7B8EGTNPSPA7FPC4Z","postgres-database-migration","Use this skill for planning, testing, and safely executing PostgreSQL schema migrations — especially when working with production data or shared databases.\n\n**Trigger when user asks to:**\n- Test a schema migration before applying it to production\n- Add, remove, or rename columns safely on a live table\n- Change a column's data type without downtime\n- Add or drop indexes, constraints, or foreign keys on large tables\n- Understand which ALTER TABLE operations lock the table\n- Roll back a failed migration\n- Plan a zero-downtime migration strategy\n- Fork a database to test a migration safely\n\nCovers: lock-level reference for every common DDL operation, safe migration patterns, fork-based testing, zero-downtime column changes, index creation, constraint addition, backfill strategies, pre\u002Fpost-migration validation, and rollback planning.","Apache-2.0","https:\u002F\u002Fgithub.com\u002Fdeadmade\u002Fdead-agent-skills\u002Fblob\u002Fmain\u002Fplugins\u002Fopt-in\u002Fimplementation\u002Fpostgres\u002Fskills\u002Fpostgres-database-migration\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fdeadmade\u002Fdead-agent-skills\u002Fblob\u002Fmain\u002Fplugins\u002Fopt-in\u002Fimplementation\u002Fpostgres\u002Fskills\u002Fpostgres-database-migration\u002FSKILL.md",[],[],{"skillNo":70,"name":71,"nameZh":6,"description":72,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":64,"licenseFileUrl":73,"sourceHtmlUrl":74,"categories":75,"keywords":76,"publishedAt":18},"01M7CVQWK20ASAZN5VETZC8J99","postgres-best-practices","Best practices and guidelines for working with Postgres. Covers schema design, indexing strategies, query optimization, migrations, and common pitfalls. Use when writing SQL, designing database schemas, optimizing queries, or setting up a Postgres database.","https:\u002F\u002Fgithub.com\u002Fdeadmade\u002Fdead-agent-skills\u002Fblob\u002Fmain\u002Fplugins\u002Fopt-in\u002Fimplementation\u002Fpostgres\u002Fskills\u002Fpostgres-best-practices\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fdeadmade\u002Fdead-agent-skills\u002Fblob\u002Fmain\u002Fplugins\u002Fopt-in\u002Fimplementation\u002Fpostgres\u002Fskills\u002Fpostgres-best-practices\u002FSKILL.md",[],[],{"skillNo":78,"name":79,"nameZh":6,"description":80,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":81,"categories":82,"keywords":83,"publishedAt":18},"01M7CVQ5CY7AQHY7A2Y99RE6A7","writing-mstest-tests","ALWAYS USE when asked to fix, rewrite, update, improve, modernize, show corrected code for, or explain existing MSTest tests or MSTest-specific configuration. Use for \"review\" when corrected code or edits are wanted, even for one pasted assertion or passing tests with bad failure output. Covers expected\u002Factual labels; generic Boolean, collection, string, numeric, null, identity, exception, hard-cast, and object[] checks; TestContext\u002Flifecycle; timeout\u002Fcancellation; OS\u002FCI conditions, retry, cleanup, parallelization, MSTest.Sdk project setup, and MSTESTxxxx. Honor the installed MSTest version. DO NOT USE to design new test cases (code-testing), perform report-only audits, create project files rather than explain MSTest setup, run tests, migrate frameworks, or handle non-MSTest\u002Fnon-.NET code.","https:\u002F\u002Fgithub.com\u002Fdeadmade\u002Fdead-agent-skills\u002Fblob\u002Fmain\u002Fplugins\u002Fopt-in\u002Fimplementation\u002Fcsharp-skills\u002Flibrary\u002Fwriting-mstest-tests\u002FSKILL.md",[],[],{"skillNo":85,"name":86,"nameZh":6,"description":87,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":88,"categories":89,"keywords":90,"publishedAt":18},"01M7CVPWJZ63GB0810F0SCGZ1K","winforms-expert","Create, modify, debug, or review Windows Forms applications only when the request contains a concrete Windows Forms marker. USE FOR: WinForms, Windows Forms, System.Windows.Forms, WinForms Form or UserControl designer files (*.Designer.cs or *.Designer.vb), Visual Studio WinForms Designer, TableLayoutPanel, BindingSource, DataGridView, Control.InvokeAsync, component-tray ownership, or custom control serialization. DO NOT USE FOR: WPF or WPF XAML, including Window.InputBindings, KeyBinding, commands, or DataContext; .NET MAUI; Avalonia; or any request where none of the listed Windows Forms markers is present.","https:\u002F\u002Fgithub.com\u002Fdeadmade\u002Fdead-agent-skills\u002Fblob\u002Fmain\u002Fplugins\u002Fopt-in\u002Fimplementation\u002Fcsharp-skills\u002Flibrary\u002Fwinforms-expert\u002FSKILL.md",[],[],{"skillNo":92,"name":93,"nameZh":6,"description":94,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":95,"categories":96,"keywords":97,"publishedAt":18},"01M7CVPR0QFZ1HMJ6GZRBQAQ7W","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 the generic Vector type, 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\u002Fdeadmade\u002Fdead-agent-skills\u002Fblob\u002Fmain\u002Fplugins\u002Fopt-in\u002Fimplementation\u002Fcsharp-skills\u002Flibrary\u002Fvectorization\u002FSKILL.md",[],[]]