Community编程与开发github.com

依赖注入模式

使用 IServiceCollection 扩展方法组织依赖注入注册。将相关服务分组为可组合的 Add* 方法,以实现干净的 Program.cs 和在测试中的可重用配置。

依赖注入模式 是什么?

这个技能专注于在 ASP.NET Core 应用程序中优雅地组织依赖注入(DI)注册。它通过引入 IServiceCollection 扩展方法模式,将相关服务分组为 `Add{Feature}Services()` 这样的方法,从而解决了 Program.cs 或 Startup.cs 文件因大量注册代码而变得臃肿难维护的问题。主要优点包括:保持 Program.cs 的简洁明了、建立清晰的业务边界、使服务配置在生产代码和测试之间可重用,以及减少合并冲突。该技能适用于 ASP.NET Core、Microsoft.Extensions.DependencyInjection、Akka.NET 以及任何使用标准 DI 容器的 .NET 应用程序。它还涵盖了与配置、选项模式、作用域生命周期管理以及 Akka.Hosting 集成的常见场景,并提供了测试、文件组织约定和避免反模式的指导。

兼容平台~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-actor-patterns 技能了解完整的 Akka.Hosting 模式。


反模式

不要:将所有注册都放在 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无状态、线程安全、创建成本高Configuration、HttpClient 工厂、缓存
Scoped每个请求有状态、数据库上下文DbContext、存储库、用户上下文
Transient轻量级、有状态、创建成本低验证器、短期助手
// SINGLETON:无状态服务,可以安全共享
services.AddSingleton<IMjmlTemplateRenderer, MjmlTemplateRenderer>();

// SCOPED:数据库访问,每个请求状态
services.AddScoped<IUserRepository, UserRepository>();

// TRANSIENT:廉价、短期
services.AddTransient<CreateUserRequestValidator>();

Scoped 服务需要作用域。 ASP.NET Core 会为每个 HTTP 请求创建一个作用域。在后台服务和 actor 中,需要手动创建作用域。

请参阅 advanced-patterns.md 了解 actor 作用域管理模式。


常见错误

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

相关技能