Token导航 LogoToken导航TokenDH.com
前端设计执行命令github未标认证来源可访问许可证需确认审计通过

maui-dependency-injection毛伊岛依赖注入

Agent Skill

maui-dependency-injection 用于处理 GitHub 仓库、Issue、Pull Request 和代码协作信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要围绕仓库状态、代码变更或协作事项进行整理时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

总安装

2,987

周安装

127

GitHub Stars

1,507

下载量

1,046
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:maui-dependency-injection(毛伊岛依赖注入)
来源仓库:https://github.com/dotnet/skills
仓库路径:skills/maui-dependency-injection
安装命令:
npx skills add https://github.com/dotnet/skills --skill maui-dependency-injection
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/dotnet/skills --skill maui-dependency-injection

简介

用于处理 GitHub 仓库、Issue 和 Pull Request 信息。

  • 适合围绕代码变更和协作事项进行整理。maui-dependency-injection 属于前端设计类 Skill,可作为该场景下的辅助能力补充。
  • 可结合来源仓库和原始 README 核验具体用法。
  • 安装前建议确认权限范围和是否会触发命令执行。
  • 维护状态不明时需人工复核功能稳定性。

SKILL.md

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

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

LifetimeWhen to UseTypical Types
AddSingleton<T>()Shared state, expensive to create, app-wide configHttpClient factory, settings service, database connection
AddTransient<T>()Lightweight, stateless, or needs a fresh instance per usePages, ViewModels, per-call API wrappers
AddScoped<T>()Per-scope lifetime with manually created IServiceScopeScoped unit-of-work (rare in MAUI)

Key rule: Register Pages and ViewModels as Transient. Register shared services as Singleton.

⚠️ Avoid AddScoped unless you manually manage IServiceScope. MAUI has no built-in request scope like ASP.NET Core. A Scoped registration without an explicit scope silently behaves as a Singleton, leading to subtle bugs.

Registration Pattern in MauiProgram.cs

public static MauiApp CreateMauiApp()
{
    var builder = MauiApp.CreateBuilder();
    builder.UseMauiApp<App>();

    // Services — Singleton for shared state
    builder.Services.AddSingleton<IDataService, DataService>();
    builder.Services.AddSingleton<ISettingsService, SettingsService>();

    // HTTP — use typed or named clients via IHttpClientFactory
    // Requires NuGet: Microsoft.Extensions.Http
    builder.Services.AddHttpClient<IApiClient, ApiClient>();

    // ViewModels — Transient for fresh state per navigation
    builder.Services.AddTransient<MainViewModel>();
    builder.Services.AddTransient<DetailViewModel>();

    // Pages — Transient so constructor injection fires each time
    builder.Services.AddTransient<MainPage>();
    builder.Services.AddTransient<DetailPage>();

    return builder.Build();
}

Constructor Injection

Inject dependencies through constructor parameters. The container resolves them automatically when the type is itself resolved from DI.

public class MainViewModel
{
    private readonly IDataService _dataService;

    public MainViewModel(IDataService dataService)
    {
        _dataService = dataService;
    }

    public async Task LoadAsync() => Items = await _dataService.GetItemsAsync();
}

ViewModel → Page Wiring

Register both Page and ViewModel. Inject the ViewModel into the Page and assign it as BindingContext:

public partial class MainPage : ContentPage
{
    public MainPage(MainViewModel viewModel)
    {
        InitializeComponent();
        BindingContext = viewModel;
    }
}

Shell Navigation Auto-Resolution

When a Page is registered in DI and as a Shell route, Shell resolves it (and its full dependency graph) automatically on navigation:

// MauiProgram.cs
builder.Services.AddTransient<DetailPage>();
builder.Services.AddTransient<DetailViewModel>();

// AppShell.xaml.cs
Routing.RegisterRoute(nameof(DetailPage), typeof(DetailPage));

// Navigate — DI resolves DetailPage + DetailViewModel
await Shell.Current.GoToAsync(nameof(DetailPage));

Platform-Specific Registration

Use preprocessor directives to register platform implementations. Always cover every target platform or provide a no-op fallback to avoid runtime null.

#if ANDROID
builder.Services.AddSingleton<INotificationService, AndroidNotificationService>();
#elif IOS || MACCATALYST
builder.Services.AddSingleton<INotificationService, AppleNotificationService>();
#elif WINDOWS
builder.Services.AddSingleton<INotificationService, WindowsNotificationService>();
#else
builder.Services.AddSingleton<INotificationService, NoOpNotificationService>();
#endif

Explicit Resolution (Last Resort)

Prefer constructor injection. Use explicit resolution only where injection is genuinely unavailable (custom handlers, platform callbacks):

// From any Element with a Handler
var service = this.Handler.MauiContext.Services.GetService<IDataService>();

For dynamic resolution, inject IServiceProvider:

public class NavigationService(IServiceProvider serviceProvider)
{
    public T ResolvePage<T>() where T : Page
        => serviceProvider.GetRequiredService<T>();
}

Interface-First Pattern for Testability

Define interfaces for every service so implementations can be swapped in tests:

public interface IDataService
{
    Task<List<Item>> GetItemsAsync();
}

// Production registration
builder.Services.AddSingleton<IDataService, DataService>();

// Test registration — swap without touching production code
var services = new ServiceCollection();
services.AddSingleton<IDataService, FakeDataService>();

Common Pitfalls

1. Singleton ViewModels Cause Stale Data

// ❌ ViewModel keeps stale state across navigations
builder.Services.AddSingleton<DetailViewModel>();

// ✅ Fresh instance each navigation
builder.Services.AddTransient<DetailViewModel>();

2. Unregistered Page Silently Skips Injection

If a Page appears in Shell XAML via <ShellContent ContentTemplate="..."> but is not registered in builder.Services, MAUI creates it with the parameterless constructor. Dependencies are silently null — no exception is thrown.

// ❌ Missing — injection silently skipped
// builder.Services.AddTransient<DetailPage>();

// ✅ Always register pages that need injection
builder.Services.AddTransient<DetailPage>();
builder.Services.AddTransient<DetailViewModel>();

3. XAML Resource Parsing vs. DI Timing

XAML resources in App.xaml are parsed during InitializeComponent() — before the container is fully available. Defer service-dependent work to CreateWindow():

public partial class App : Application
{
    private readonly IServiceProvider _services;

    public App(IServiceProvider services)
    {
        _services = services;
        InitializeComponent();
    }

    protected override Window CreateWindow(IActivationState? activationState)
    {
        // Safe — container is fully built
        // Requires: builder.Services.AddTransient<AppShell>() in MauiProgram.cs
        var appShell = _services.GetRequiredService<AppShell>();
        return new Window(appShell);
    }
}

4. Service Locator Anti-Pattern

// ❌ Hides dependencies, hard to test
var svc = this.Handler.MauiContext.Services.GetService<IDataService>();

// ✅ Constructor injection — explicit and testable
public class MyViewModel(IDataService dataService) { }

5. Missing Platform in Conditional Registration

Forgetting a platform in #if blocks means GetService<T>() returns null at runtime on that platform. Always include an #else fallback or cover every target.

6. AddScoped Without Manual Scope

AddScoped in MAUI without creating IServiceScope manually gives Singleton behavior silently. Use AddTransient or AddSingleton instead unless you explicitly manage scopes.


Checklist

  • Every Page and ViewModel that needs injection is registered in MauiProgram.cs
  • Pages and ViewModels use AddTransient; shared services use AddSingleton
  • Constructor injection used everywhere possible; service locator only as last resort
  • Interfaces defined for services that need test substitution
  • Platform-specific #if registrations cover all target platforms or include a fallback
  • Service-dependent work deferred to CreateWindow(), not run during XAML parse
  • AddScoped only used alongside manually created IServiceScope

References

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Codex

33.02%
按下载量换算345

Claude

27.49%
按下载量换算288

Cursor

20.91%
按下载量换算219

Gemini CLI

9.44%
按下载量换算99

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

执行命令

安装流程涉及命令执行,可能通过 npx skills add https://github.com/dotnet/skills --skill maui-dependency-injection 联网下载 Skill 或依赖。用户安装前应确认命令来源、仓库内容和执行环境。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills