Community程式設計與開發github.com

依賴注入模式

使用 IServiceCollection 擴充方法組織 DI 註冊。將相關服務分組到可組合的 Add* 方法中,以保持 Program.cs 簡潔,並在測試中實現可重複使用。

依賴注入模式 是什麼?

此技能教授如何透過擴充方法(Extension Method Pattern)組織 ASP.NET Core 中的依賴注入(DI)註冊。其核心原理是將相關服務分組到如 `AddUserServices()` 之類的 `Add*` 方法中,避免在 `Program.cs` 中出現數百行難以維護的註冊代碼。這種模式不僅讓服務註冊更具可讀性和組合性,還能直接在測試中重用生產環境的配置,只需覆蓋需要變更的部分。技能支援標準 ASP.NET Core 以及 Akka.NET(透過 `AkkaConfigurationBuilder`),並涵蓋了階層式擴充(Layered Extensions)、配置接收、生命週期管理(Singleton、Scoped、Transient)以及常見的反模式(如將 Scoped 服務注入 Singleton、遺漏背景服務的 Scope 建立)。本技能適合需要清理大型 Web 應用程式註冊代碼、希望在測試中動態調整 DI 配置、或正在設計與 `Microsoft.Extensions.DependencyInjection` 整合的函式庫的開發者與 AI Agent。

相容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/Aaronontheweb/dotnet-skills/tree/main/skills/microsoft-extensions-dependency-injection

Installed? Explore more 程式設計與開發 skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

依賴注入模式 是做什麼的?

何時使用此技能

在以下情況使用此技能:

  • 組織 ASP.NET Core 應用程式中的服務註冊
  • 避免 Program.cs/Startup.cs 檔案因數百行註冊而變得龐大
  • 讓服務組態在生產環境與測試之間可重複使用
  • 設計與 Microsoft.Extensions.DependencyInjection 整合的函式庫

參考文件

  • advanced-patterns.md:使用 DI 擴充進行測試、Akka.NET Actor 範圍管理、條件式/工廠/鍵控註冊模式

問題

未經組織時,Program.cs 會變得難以管理:

// 糟糕:200 多行雜亂無章的註冊
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddScoped<IUserRepository, UserRepository>();
builder.Services.AddScoped<IOrderRepository, OrderRepository>();
builder.Services.AddScoped<IProductRepository, ProductRepository>();
builder.Services.AddScoped<IUserService, UserService>();
// ... 再 150 行 ...

問題:難以找到相關註冊、沒有明確邊界、無法在測試中重複使用、合併衝突頻繁。


解決方案:擴充方法組合

將相關註冊分組到擴充方法中:

// 良好:乾淨、可組合的 Program.cs
var builder = WebApplication.CreateBuilder(args);

builder.Services
    .AddUserServices()
    .AddOrderServices()
    .AddEmailServices()
    .AddPaymentServices()
    .AddValidators();

var app = builder.Build();

擴充方法模式

基本結構

namespace MyApp.Users;

public static class UserServiceCollectionExtensions
{
    public static IServiceCollection AddUserServices(this IServiceCollection services)
    {
        services.AddScoped<IUserRepository, UserRepository>();
        services.AddScoped<IUserReadStore, UserReadStore>();
        services.AddScoped<IUserWriteStore, UserWriteStore>();
        services.AddScoped<IUserService, UserService>();
        services.AddScoped<IUserValidationService, UserValidationService>();

        return services;
    }
}

搭配組態

namespace MyApp.Email;

public static class EmailServiceCollectionExtensions
{
    public static IServiceCollection AddEmailServices(
        this IServiceCollection services,
        string configSectionName = "EmailSettings")
    {
        services.AddOptions<EmailOptions>()
            .BindConfiguration(configSectionName)
            .ValidateDataAnnotations()
            .ValidateOnStart();

        services.AddSingleton<IMjmlTemplateRenderer, MjmlTemplateRenderer>();
        services.AddSingleton<IEmailLinkGenerator, EmailLinkGenerator>();
        services.AddScoped<IUserEmailComposer, UserEmailComposer>();
        services.AddScoped<IEmailSender, SmtpEmailSender>();

        return services;
    }
}

檔案組織

將擴充方法放置在它們所註冊服務的附近:

src/
  MyApp.Api/
    Program.cs                    # 組合所有 Add* 方法
  MyApp.Users/
    Services/
      UserService.cs
    UserServiceCollectionExtensions.cs   # AddUserServices()
  MyApp.Orders/
    OrderServiceCollectionExtensions.cs  # AddOrderServices()
  MyApp.Email/
    EmailServiceCollectionExtensions.cs  # AddEmailServices()

慣例:將 {Feature}ServiceCollectionExtensions.cs 放在功能服務的旁邊。


命名慣例

模式用途
Add{Feature}Services()一般功能註冊
Add{Feature}()無歧義時的簡寫
Configure{Feature}()主要用於設定選項時
Use{Feature}()中介軟體(適用於 IApplicationBuilder)

測試優勢

Add* 模式讓您在測試中重複使用生產環境的組態,僅覆蓋需要變更的部分。可搭配 WebApplicationFactory、Akka.Hosting.TestKit 及獨立 ServiceCollection 使用。

完整測試範例請參閱 advanced-patterns.md。


階層式擴充

對於大型應用程式,可以階層式組合擴充:

public static class AppServiceCollectionExtensions
{
    public static IServiceCollection AddAppServices(this IServiceCollection services)
    {
        return services
            .AddDomainServices()
            .AddInfrastructureServices()
            .AddApiServices();
    }
}

public static class DomainServiceCollectionExtensions
{
    public static IServiceCollection AddDomainServices(this IServiceCollection services)
    {
        return services
            .AddUserServices()
            .AddOrderServices()
            .AddProductServices();
    }
}

Akka.Hosting 整合

相同的模式也適用於 Akka.NET Actor 組態:

public static class OrderActorExtensions
{
    public static AkkaConfigurationBuilder AddOrderActors(
        this AkkaConfigurationBuilder builder)
    {
        return builder
            .WithActors((system, registry, resolver) =>
            {
                var orderProps = resolver.Props<OrderActor>();
                var orderRef = system.ActorOf(orderProps, "orders");
                registry.Register<OrderActor>(orderRef);
            });
    }
}

// Program.cs 中的用法
builder.Services.AddAkka("MySystem", (builder, sp) =>
{
    builder
        .AddOrderActors()
        .AddInventoryActors()
        .AddNotificationActors();
});

完整的 Akka.Hosting 模式請參閱 akka-hosting-actor-patterns 技能。


反模式

不要:在 Program.cs 中註冊所有東西

// 糟糕:200+ 行註冊的龐大 Program.cs

不要:建立過於通用的擴充

// 糟糕:太模糊,無法傳達註冊了什麼
public static IServiceCollection AddServices(this IServiceCollection services) { ... }

不要:隱藏重要組態

// 糟糕:埋藏設定
public static IServiceCollection AddDatabase(this IServiceCollection services)
{
    services.AddDbContext<AppDbContext>(options =>
        options.UseSqlServer("hardcoded-connection-string"));  // 隱藏了!
}

// 良好:明確接收組態
public static IServiceCollection AddDatabase(
    this IServiceCollection services,
    string connectionString)
{
    services.AddDbContext<AppDbContext>(options =>
        options.UseSqlServer(connectionString));
}

最佳實務摘要

實務優點
將相關服務分組到 Add* 方法乾淨的 Program.cs,清晰的邊界
將擴充放在所註冊服務的附近易於尋找和維護
返回 IServiceCollection 以支援鏈式呼叫流暢的 API
接受組態參數靈活性
使用一致的命名(Add{Feature}Services)可發現性
透過重複使用生產擴充進行測試信心提升,減少重複

生命週期管理

生命週期何時使用範例
Singleton無狀態、執行緒安全、建立成本高昂組態、HttpClient 工廠、快取
Scoped每個請求有狀態、資料庫內容DbContext、儲存庫、使用者內容
Transient輕量、有狀態、建立成本低廉驗證器、短期輔助程式
// SINGLETON:無狀態服務,可安全共用
services.AddSingleton<IMjmlTemplateRenderer, MjmlTemplateRenderer>();

// SCOPED:資料庫存取,每個請求狀態
services.AddScoped<IUserRepository, UserRepository>();

// TRANSIENT:便宜、短期存在
services.AddTransient<CreateUserRequestValidator>();

Scoped 服務需要一個範圍。 ASP.NET Core 會為每個 HTTP 請求自動建立一個。在背景服務和 Actor 中,請手動建立範圍。

Actor 範圍管理模式請參閱 advanced-patterns.md。


常見錯誤

將 Scoped 注入 Singleton

// 糟糕:Singleton 捕獲了 Scoped 服務 - DbContext 已過時!
public class CacheService  // 註冊為 Singleton
{
    private readonly IUserRepository _repo;  // Scoped - 在啟動時被捕獲!
}

// 良好:注入 IServiceProvider,每個操作建立範圍
public class CacheService
{
    private readonly IServiceProvider _serviceProvider;

    public async Task<User> GetUserAsync(string id)
    {
        using var scope = _serviceProvider.CreateScope();
        var repo = scope.ServiceProvider.GetRequiredService<IUserRepository>();
        return await repo.GetByIdAsync(id);
    }
}

背景工作中缺少範圍

// 糟糕:Scoped 服務沒有範圍
public class BadBackgroundService : BackgroundService
{
    private readonly IOrderService _orderService;  // Scoped - 會擲回例外!
}

// 良好:為每個工作單位建立範圍
public class GoodBackgroundService : BackgroundService
{
    private readonly IServiceScopeFactory _scopeFactory;

    protected override async Task ExecuteAsync(CancellationToken ct)
    {
        using var scope = _scopeFactory.CreateScope();
        var orderService = scope.ServiceProvider.GetRequiredService<IOrderService>();
        // ...
    }
}

資源

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

akka-hosting-actor-patterns

Patterns for building entity actors with Akka.Hosting - GenericChildPerEntityParent, message extractors, cluster sharding abstraction, akka-reminders, and ITimeProvider. Supports both local testing and clustered production modes.

akka-net-aspire-configuration

Configure Akka.NET with .NET Aspire for local development and production deployments. Covers actor system setup, clustering, persistence, Akka.Management integration, and Aspire orchestration patterns.

akka-net-best-practices

Critical Akka.NET best practices including EventStream vs DistributedPubSub, supervision strategies, error handling, Props vs DependencyResolver, work distribution patterns, and cluster/local mode abstractions for testability.

akka-net-management

Akka.Management for cluster bootstrapping, service discovery (Kubernetes, Azure, Config), health checks, and dynamic cluster formation without static seed nodes.

akka-net-testing-patterns

Write unit and integration tests for Akka.NET actors using modern Akka.Hosting.TestKit patterns. Covers dependency injection, TestProbes, persistence testing, and actor interaction verification. Includes guidance on when to use traditional TestKit.

api-design

Design stable, compatible public APIs using extend-only design principles. Manage API compatibility, wire compatibility, and versioning for NuGet packages and distributed systems.

aspire-configuration

Configure Aspire AppHost to emit explicit app config via environment variables; keep app code free of Aspire clients and service discovery.

aspire-integration-testing

Write integration tests using .NET Aspire

aspire-service-defaults

Create a shared ServiceDefaults project for Aspire applications. Centralizes OpenTelemetry, health checks, resilience, and service discovery configuration across all services.

crap-analysis

Analyze code coverage and CRAP (Change Risk Anti-Patterns) scores to identify high-risk code. Use OpenCover format with ReportGenerator for Risk Hotspots showing cyclomatic complexity and untested code paths.

csharp-concurrency-patterns

Choosing the right concurrency abstraction in .NET - from async/await for I/O to Channels for producer/consumer to Akka.NET for stateful entity management. Avoid locks and manual synchronization unless absolutely necessary.

database-performance

Database access patterns for performance. Separate read/write models, avoid N+1 queries, use AsNoTracking, apply row limits, and never do application-side joins. Works with EF Core and Dapper.

dotnet-devcert-trust

Diagnose and fix .NET HTTPS dev certificate trust issues on Linux. Covers the full certificate lifecycle from generation to system CA bundle inclusion, with distro-specific guidance for Ubuntu, Fedora, Arch, and WSL2.

dotnet-local-tools

Managing local .NET tools with dotnet-tools.json for consistent tooling across development environments and CI/CD pipelines.

dotnet-project-structure

Modern .NET project structure including .slnx solution format, Directory.Build.props, central package management, SourceLink, version management with RELEASE_NOTES.md, and SDK pinning with global.json.

dotnet-slopwatch

Use Slopwatch to detect LLM reward hacking in .NET code changes. Run after every code modification to catch disabled tests, suppressed warnings, empty catch blocks, and other shortcuts that mask real problems.

efcore-patterns

Entity Framework Core best practices including NoTracking by default, query splitting for navigation collections, migration management, dedicated migration services, and common pitfalls to avoid.

ilspy-decompile

Understand implementation details of .NET code by decompiling assemblies. Use when you want to see how a .NET API works internally, inspect NuGet package source, view framework implementation, or understand compiled .NET binaries.

mailpit-integration

Test email sending locally using Mailpit with .NET Aspire. Captures all outgoing emails without sending them. View rendered HTML, inspect headers, and verify delivery in integration tests.

marketplace-publishing

Workflow for publishing skills and agents to the dotnet-skills Claude Code marketplace. Covers adding new content, updating plugin.json, validation, and release tagging.

相關技能