maui-dependency-injection
Qué hace
Esta skill configura la inyección de dependencias en apps .NET MAUI, donde los servicios se registran al arrancar y se entregan a las páginas y view models que los necesitan. Está pensada para desarrolladores que organizan los servicios de una app MAUI.
Cuándo usarla
- ✓Cuando quieres registrar un servicio, una página o un view model en una app .NET MAUI.
- ✓Cuando necesitas elegir entre tiempos de vida singleton, transient y scoped.
- ✓Cuando quieres que un servicio funcione con la navegación de Shell y sea fácil de probar.
Link de la skill
https://github.com/dotnet/skills/blob/main/plugins/dotnet-maui/skills/maui-dependency-injection/SKILL.mdCópialo y pégalo en tu IA (Claude, ChatGPT o Cursor) pidiéndole que siga las instrucciones.
Cómo usar
La forma más fácil: copia el mensaje y pégalo en tu IA. Ella lee la skill y sigue las instrucciones.
Mensaje listo para pegar
Para Claude Code, Codex o Cursor: ejecútalo en la carpeta del proyecto y la skill queda instalada.
Descarga el SKILL.md y ponlo en la carpeta de skills de tu agente.
Ejemplo de qué pedirle a la IA
“Registra mi cliente de API como singleton e inyéctalo en los view models de MAUI.”
5 skills nuevas por semana. 1 minuto de lectura.
Cómo funciona
El agente añade los registros al archivo de arranque de la app, elige un tiempo de vida para cada servicio y conecta la inyección por constructor para páginas y view models.
Contenido técnico (SKILL.md original)
Texto original del autor, en inglés, directo de 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, andAddScoped - Wiring constructor injection for Pages and ViewModels
- Leveraging Shell navigation to auto-resolve DI-registered Pages
- Registering platform-specific service implementations with
#ifdirectives - 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.csfile - 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
- Identify all services, ViewModels, and Pages that need to participate in dependency injection.
- Choose the correct lifetime for each type —
AddSingletonfor shared services,AddTransientfor Pages and ViewModels. - Register all types in
MauiProgram.CreateMauiApp()onbuilder.Services, grouping by category (services, HTTP, ViewModels, Pages). - Register Pages as Shell routes in
AppShell.xaml.csso Shell navigation auto-resolves the full dependency graph. - Wire each Page to its ViewModel via constructor injection, assigning the ViewModel as
BindingContext. - Add platform-specific registrations with
#ifdirectives, ensuring every target platform is covered or has a fallback. - Verify resolution works by running the app and confirming no
nulldependencies 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 |
Preguntas frecuentes
¿Dónde se registran los servicios?
Los registros van en el archivo MauiProgram de la app, en la colección de servicios.
¿Qué es el tiempo de vida transient?
Crea una instancia nueva cada vez que se solicita el servicio.
¿Cubre los mocks para pruebas?
Cubre diseños comprobables, pero las herramientas de mocks son aparte.
Detalles
Descripción original del autor
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
Popularidad
- Estrellas en GitHub
- 5,8 mil
- Posición en el ranking
- #14586
- Licencia
- MIT
- Actualizada
- 2/11/2026
Comentarios
- …
Más skills de este repositorio
create-custom-agent
5,8 milAyuda a tu agente a crear archivos de agentes personalizados de VS Code, con sus propias herramientas, instrucciones y traspasos a otros agentes.
create-skill
5,8 milAyuda a tu agente a crear una skill nueva de agente con un nombre válido, una descripción de activación clara y un archivo SKILL.md que siga el estándar.
csharp-scripts
5,8 milAyuda a tu agente a ejecutar un pequeño programa en C# como un único archivo con la herramienta de línea de comandos de .NET, sin crear un proyecto completo.
dotnet-pinvoke
5,8 milAyuda a tu agente a llamar correctamente a librerías nativas de C o C++ desde .NET, cubriendo firmas, manejo de cadenas, memoria y handles seguros.
Skills parecidas
android-clean-architecture
280 milHace que tu agente organice proyectos de Android de forma eficiente. Estructura el código para facilitar el mantenimiento y el desarrollo de nuevas funciones.
compose-multiplatform-patterns
280 milAyuda a tu agente a usar patrones de Compose Multiplatform y Jetpack Compose en proyectos KMP, incluyendo estado, navegación, temas y rendimiento.
dart-flutter-patterns
280 milHace que tu agente escriba código para apps de Dart y Flutter. Usa patrones modernos para crear apps robustas y fáciles de mantener.