跳到正文
Skillpedia
移动应用5.8k · #14586

maui-dependency-injection

它能做什么

这项技能在 .NET MAUI 应用中设置依赖注入,服务在启动时注册,并交给需要它们的页面和视图模型。适合在 MAUI 应用中组织服务的开发者。

适用场景

  • ✓当你希望在 .NET MAUI 应用中注册服务、页面或视图模型时。
  • ✓当你需要在单例、瞬时和作用域生命周期之间做选择的时候。
  • ✓当你希望服务能与 Shell 导航配合,并且易于测试的时候。

技能链接

https://github.com/dotnet/skills/blob/main/plugins/dotnet-maui/skills/maui-dependency-injection/SKILL.md

复制后粘贴给你的 AI(Claude、ChatGPT 或 Cursor),让它按照说明操作。

使用方法

最简单的方法:复制下面的消息,粘贴给你的 AI。它会读取这个技能并按说明操作。

可直接粘贴的消息

请用这个技能帮我:https://github.com/dotnet/skills/blob/main/plugins/dotnet-maui/skills/maui-dependency-injection/SKILL.md 阅读该链接中的 SKILL.md 文件,并在我的任务中按照它的说明来做。
想让你的 AI 自己找到这样的技能吗?安装免费的 Skillpedia MCP:只需一行,每次任务前它都会在 15,000+ 个技能中搜索。1 分钟完成安装 →

可以这样问 AI

“请把我的 API 客户端注册为单例,并将其注入到我的 MAUI 视图模型中。”

每周 5 个新技能,1 分钟读完。

工作原理

智能体会把注册添加到应用的启动文件中,为每个服务选择生命周期,并为页面和视图模型配置构造函数注入。

技术内容(原始 SKILL.md)

作者在 GitHub 上的英文原文。

Dependency Injection in .NET MAUI

.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.

When to Use

  • Registering services, ViewModels, and Pages in MauiProgram.cs
  • Choosing between AddSingleton, AddTransient, and AddScoped
  • Wiring constructor injection for Pages and ViewModels
  • Leveraging Shell navigation to auto-resolve DI-registered Pages
  • Registering platform-specific service implementations with #if directives
  • Designing interfaces for testable service layers

When Not to Use

  • XAML data-binding syntax or compiled bindings — use the maui-data-binding skill
  • Shell route registration and query parameters — use the maui-shell-navigation skill
  • Mocking frameworks or test runners — use standard .NET testing tools (xUnit, NUnit, MSTest) and mocking libraries (NSubstitute, Moq)

Inputs

  • A .NET MAUI project with a MauiProgram.cs file
  • Knowledge of which services, ViewModels, and Pages need registration
  • Target platforms (Android, iOS, Mac Catalyst, Windows) for conditional registrations

Rules That Change the Answer

Situation Do this Why
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)
Registering shared/expensive state AddSingleton One instance app-wide (settings, DB connection, HttpClient handler)
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
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
Platform-specific implementation #if per platform with every platform covered A missing platform branch leaves the service unregistered and throws at resolution time

Do not introduce DI into a project that isn't using it, swap a working service lifetime, or add an interface purely for symmetry — only when the user asked or it fixes a real defect.

Answer narrowly, but completely. When you recommend a lifetime change, show the registration code, and give the realistic alternatives rather than a single verdict — for a unit-of-work or DbContext question that means AddTransient, an explicit IServiceScopeFactory.CreateScope(), and the factory pattern (AddDbContextFactory), with a note on when each fits. A one-line prescription is usually a worse answer than a short menu with trade-offs.

// Explicit scope when you genuinely need unit-of-work semantics
using var scope = scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<MyDbContext>();

Workflow

  1. Identify all services, ViewModels, and Pages that need to participate in dependency injection.
  2. Choose the correct lifetime for each type — AddSingleton for shared services, AddTransient for Pages and ViewModels.
  3. Register all types in MauiProgram.CreateMauiApp() on builder.Services, grouping by category (services, HTTP, ViewModels, Pages).
  4. Register Pages as Shell routes in AppShell.xaml.cs so Shell navigation auto-resolves the full dependency graph.
  5. Wire each Page to its ViewModel via constructor injection, assigning the ViewModel as BindingContext.
  6. Add platform-specific registrations with #if directives, ensuring every target platform is covered or has a fallback.
  7. Verify resolution works by running the app and confirming no null dependencies or missing-registration exceptions at runtime.

Lifetime Selection

Lifetime When to Use Typical Types
AddSingleton<T>() Shared state, expensive to create, app-wide config HttpClient factory, settings service, database connection
AddTransient<T>() Lightweight, stateless, or needs a fresh instance
常见问题

服务在哪里注册?

注册内容写在应用的 MauiProgram 文件中的服务集合里。

什么是瞬时生命周期?

每次请求该服务时都会得到一个新的实例。

它涵盖测试中的模拟吗?

它涵盖可测试的设计,但模拟工具是另外的内容。

详情

作者的原始描述

Guidance for configuring dependency injection in .NET MAUI apps — service registration in MauiProgram.cs, lifetime selection (Singleton / Transient / 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-nav

repo: dotnet/skills

热度

GitHub 星标
5.8k
排名
#14586
许可证
MIT
更新时间
2026/11/2

这个技能有用吗?

0

登录 后即可投票。

评论

  • …

同一仓库的更多技能

相似技能