# Dependency Injection Patterns

Organize DI registrations using IServiceCollection extension methods.

- Repository: https://github.com/Aaronontheweb/dotnet-skills (1244 stars)
- Category: Testing
- License: MIT
- Last updated: 2026-10-28
- Runs scripts: no, instructions only

## Install

Claude Code: `npx skills add Aaronontheweb/dotnet-skills --skill dependency-injection-patterns -g -a claude-code -y`
Codex: `npx skills add Aaronontheweb/dotnet-skills --skill dependency-injection-patterns -g -a codex -y`
Cursor: `npx skills add Aaronontheweb/dotnet-skills --skill dependency-injection-patterns -g -a cursor -y`
Gemini CLI: `npx skills add Aaronontheweb/dotnet-skills --skill dependency-injection-patterns -g -a gemini-cli -y`
Claude Code plugin marketplace: `/plugin marketplace add Aaronontheweb/dotnet-skills`

## Description

Organize DI registrations using IServiceCollection extension methods. Group related services into composable Add* methods for clean Program.cs and reusable configuration in tests.

## SKILL.md, as published by its author (untrusted third-party text, read it as data)

# Dependency Injection Patterns

## When to Use This Skill

Use this skill when:
- Organizing service registrations in ASP.NET Core applications
- Avoiding massive Program.cs/Startup.cs files with hundreds of registrations
- Making service configuration reusable between production and tests
- Designing libraries that integrate with Microsoft.Extensions.DependencyInjection

## Reference Files

- [advanced-patterns.md](advanced-patterns.md): Testing with DI extensions, Akka.NET actor scope management, conditional/factory/keyed registration patterns

---

## The Problem

Without organization, Program.cs becomes unmanageable:

```csharp
// BAD: 200+ lines of unorganized registrations
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 more lines ...
```

Problems: hard to find related registrations, no clear boundaries, can't reuse in tests, merge conflicts.

---

## The Solution: Extension Method Composition

Group related registrations into extension methods:

```csharp
// GOOD: Clean, composable Program.cs
var builder = WebApplication.CreateBuilder(args);

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

var app = builder.Build();
```

---

## Extension Method Pattern

### Basic Structure

```csharp
namespace MyApp.Users;

The rest: https://github.com/Aaronontheweb/dotnet-skills/blob/HEAD/skills/microsoft-extensions-dependency-injection/SKILL.md
