dotnet-csharp-dependency-injection
Installation
SKILL.md
dotnet-csharp-dependency-injection
Advanced Microsoft.Extensions.DependencyInjection patterns for .NET applications. Covers service lifetimes, keyed services (net8.0+), decoration, factory delegates, scope validation, and hosted service registration.
Cross-references: [skill:dotnet-csharp-async-patterns] for BackgroundService async patterns, [skill:dotnet-csharp-configuration] for IOptions<T> binding.
Service Lifetimes
| Lifetime | Registration | When to Use |
|---|---|---|
| Transient | AddTransient<T>() |
Lightweight, stateless services. New instance per injection. |
| Scoped | AddScoped<T>() |
Per-request state (EF Core DbContext, unit of work). |
| Singleton | AddSingleton<T>() |
Thread-safe, stateless, or shared state (caches, config). |
Lifetime Mismatches (Captive Dependencies)
Never inject a shorter-lived service into a longer-lived one: