Dependency Injection
Dependency injection is the application-composition technique built into modern .NET hosting. It makes required collaborators explicit, centralizes object construction, manages reuse and disposal, and lets application code depend on stable contracts at meaningful boundaries.
Overview
The built-in .NET dependency-injection container turns service registrations into object graphs at a composition root. Constructor injection declares required collaborators, while singleton, scoped, and transient lifetimes express how long instances are reused and who disposes them. ASP.NET Core creates a scope for each request; workers, console applications, queues, and scheduled jobs must create scopes for their own logical operations. Production design also includes validated options, feature-level registration extensions, keyed services for named implementations, container validation, and tests that prove lifetime behavior. DI improves replaceability and ownership only when dependencies remain explicit: resolving services from a global provider, capturing scoped instances in singletons, injecting factories everywhere, or adding interfaces without a real boundary simply moves coupling into harder-to-see runtime configuration.
What you will learn
- Explain inversion of control, dependency inversion, dependency injection, and the composition root without treating them as synonyms.
- Choose singleton, scoped, and transient lifetimes from ownership, thread-safety, state, and disposal requirements.
- Organize registrations by feature while keeping application services free of service-location calls.
- Create and dispose explicit scopes for workers, message handlers, console tools, and scheduled operations.
- Use validated options, keyed services, factories, and multiple implementations only where each solves a concrete composition problem.
- Validate, test, diagnose, and observe object graphs before lifetime defects reach production.
Prerequisites
- Comfort with C# classes, interfaces, constructors, generics, IDisposable, and async disposal.
- Basic familiarity with .NET hosting, configuration, logging, and application startup.
- An understanding that database contexts, HTTP handlers, caches, and other resources have different ownership and concurrency rules.
When to use Dependency Injection
Good fit
- Applications with a composition root where framework entry points need services assembled from configuration, infrastructure, and application policy.
- Components with meaningful replacement boundaries, multiple implementations, environment-specific adapters, or focused test doubles.
- Hosted workloads that benefit from container-owned lifetime, disposal, options, logging, and framework integrations.
Choose another approach when
- Using the container inside domain entities, value objects, or static helpers; construct simple objects directly and keep dependencies explicit.
- Creating an interface for every class when there is no substitution, boundary, or testing need; concrete constructor injection is valid.
- Treating DI as a substitute for modular design: a container can construct a tightly coupled graph but cannot make its responsibilities coherent.
Key concepts
Framework or host code controls application activation and supplies collaborators instead of each service constructing its own dependencies.
A small startup boundary selects implementations, binds configuration, and assembles features; business code should not know how the container is configured.
Required collaborators appear in the constructor, making object contracts reviewable and allowing incomplete instances to be rejected at creation.
One instance is reused by the root provider and all scopes. The service must be thread-safe and may depend only on singleton-safe collaborators.
One instance is reused inside a logical operation. Web requests get scopes automatically; background operations must create and dispose them explicitly.
A new instance is produced for each resolution. Transient does not mean free: disposable transients are retained for disposal by the resolving scope.
The provider disposes instances it creates when their owning scope or root provider ends; callers should not dispose container-owned services independently.
Typed options separate configuration from behavior and can fail startup when required values or ranges are invalid.
Keyed registrations select named strategies, while IEnumerable<T> composes all implementations; both should preserve explicit application dependencies.
ValidateOnBuild and ValidateScopes detect constructability and common captive dependencies, but runtime-created branches and semantic mistakes still require tests.
Architecture
The host builds a validated root provider. Each entry point opens or receives an operation scope, and the container constructs application services plus their infrastructure adapters within that ownership boundary.
Conceptual architecture · Adapt to your system context
Implementation walkthrough
Design the ownership model before choosing registration methods. Start with the entry point and logical operation, then register a graph whose lifetimes can only flow from shorter-lived consumers toward equally long or longer-lived dependencies.
- 01Identify the composition root
Keep host creation and top-level feature registration in startup code. Move cohesive registrations into AddFeature extension methods without hiding runtime service resolution.
- 02Define real dependency boundaries
Inject concrete classes by default and introduce interfaces for external adapters, multiple strategies, stable module contracts, or focused test substitution.
- 03Choose lifetimes from ownership
Use singleton for thread-safe process-wide state, scoped for one request or operation, and transient for lightweight independent collaborators; include everything each service captures.
- 04Bind and validate configuration
Register typed options, validate ranges and allowed values, and use ValidateOnStart when the process cannot work correctly with invalid configuration.
- 05Compose variants explicitly
Use IEnumerable<T> for ordered pipelines, keyed services for named strategies, and factories when selection needs runtime data or controlled object creation.
- 06Create non-web scopes
Inject IServiceScopeFactory into the worker or runner, open one async scope per message, job, batch, or command, resolve the scoped entry point, and dispose the scope.
- 07Validate and exercise the graph
Enable ValidateOnBuild and ValidateScopes in development and tests, then resolve real entry points and test configuration, identity, disposal, and all keyed branches.
Code example
The dedicated sample groups feature registrations, validates options, makes three lifetimes explicit, and registers named notification strategies with keyed services.
public static IServiceCollection AddFulfillment(
this IServiceCollection services, IConfiguration configuration)
{
services.AddOptions<FulfillmentOptions>()
.Bind(configuration.GetSection(FulfillmentOptions.SectionName))
.Validate(o => o.MaximumQuantity is > 0 and <= 1_000,
"MaximumQuantity must be between 1 and 1000.")
.ValidateOnStart();
services.AddSingleton<ApplicationIdentity>();
services.AddScoped<OperationScope>();
services.AddTransient<ActivityIdentity>();
services.AddScoped<IOrderRepository, InMemoryOrderRepository>();
services.AddKeyedSingleton<INotificationChannel, EmailNotificationChannel>("email");
services.AddKeyedSingleton<INotificationChannel, SmsNotificationChannel>("sms");
services.AddScoped<FulfillmentProcessor>();
return services;
}Testing strategy
Test the composition contract as well as individual service behavior. A unit test with manually constructed objects cannot prove registration completeness, keyed selection, scope isolation, or disposal.
- Build a ServiceProvider with ValidateOnBuild and ValidateScopes enabled, then resolve each application entry point inside its intended scope.
- Assert singleton identity across scopes, scoped identity within and across operations, and transient identity across resolutions.
- Exercise every keyed service or IEnumerable<T> pipeline branch so missing registrations and wrong keys fail before production.
- Verify option validation with missing, malformed, boundary, and valid values; start a Host when ValidateOnStart behavior is the contract.
- Track disposal of scoped and transient resources on success, exception, and cancellation, and add integration tests where framework-created scopes matter.
Security considerations
DI controls construction, not trust. Registrations can accidentally broaden access, retain sensitive state, or select privileged implementations, so security boundaries must remain explicit and testable.
- Do not inject a root IServiceProvider or broad service locator into domain and application code; it hides capabilities and makes authorization paths difficult to review.
- Never store request identity, tokens, tenant data, or mutable user state in singleton services unless the data is isolated, bounded, and concurrency-safe.
- Keep secrets in dedicated providers or options with restricted logging; avoid dumping option objects or complete service graphs into diagnostics.
- Treat keyed or factory-selected implementations as policy decisions when variants have different privileges, networks, or data access, and test unauthorized selections.
- Register authorization handlers and infrastructure clients with the documented framework lifetimes, but enforce authorization at the operation boundary rather than assuming injection grants permission.
Performance and scalability
Resolution is normally small compared with I/O, but oversized graphs, expensive constructors, disposable transient capture, and unnecessary scopes can add startup time, allocation, memory retention, and contention.
- Keep constructors cheap and side-effect free; defer network calls, database access, and expensive initialization to explicit asynchronous operations.
- Do not register a service as singleton merely to avoid allocation; first prove thread safety, captured lifetime compatibility, state bounds, and measured value.
- Watch for large numbers of disposable transient objects resolved from the root because the provider retains them until shutdown.
- Prefer direct constructor dependencies over repeated provider lookups, reflection-driven activation, or nested factories in hot paths; measure with representative graphs.
- Keep scopes aligned to meaningful operations rather than individual helper calls, and observe resolution failures, allocations, startup duration, and retained objects when diagnosing costs.
Deployment and operations
The graph can vary by environment, configuration, trimming, and hosting model. Validate the same registrations and published artifact that production will execute.
- Run graph-validation and composition tests for each supported environment or feature combination; development-only registrations can hide production failures.
- Fail deployment startup for invalid required options and expose readiness only after mandatory dependencies and initialization are usable.
- Test reflection-based registration scanning under trimming or native AOT, heed analyzer warnings, and prefer explicit or source-generated registrations when discovery is fragile.
- Ensure graceful shutdown disposes the root provider after hosted operations stop, and allow scoped asynchronous resources to finish or cancel within the shutdown budget.
- Record ownership for externally managed clients, pools, and handles; avoid disposing objects that the container or a framework factory owns.
Common problems and fixes
A scoped service behaves like a singleton or leaks one user's state into another operation.
Likely cause: A singleton captured the scoped instance, the service was resolved from the root provider, or a background loop reused one scope.
Fix: Enable ValidateScopes, inject IServiceScopeFactory into the worker, create one scope per operation, and remove mutable request state from singletons.
No service for type X has been registered or a constructor cannot be activated.
Likely cause: A feature registration was omitted, an implementation is inaccessible, or multiple constructors make activation ambiguous.
Fix: Resolve the real entry point in a ValidateOnBuild test, call the feature registration at the composition root, and keep one unambiguous public constructor.
Configuration errors appear only on the first request.
Likely cause: Options were bound without validation or validation was deferred until IOptions.Value was first accessed.
Fix: Add semantic validators and ValidateOnStart, then test host startup with production-shaped configuration.
Memory grows even though transient services should be short lived.
Likely cause: Disposable transients were resolved from the root, scopes were not disposed, or a singleton retained transient instances or unbounded state.
Fix: Inspect ownership and heap roots, resolve disposable services in bounded scopes, dispose every scope, and replace accidental root resolution.
The wrong keyed implementation is used or a runtime key fails.
Likely cause: String keys drifted between registration and resolution or selection policy was scattered across callers.
Fix: Centralize keys and selection, prefer typed enums or a focused dispatcher at the application boundary, and test every supported variant.
A singleton fails intermittently under load.
Likely cause: The instance or one of its captured dependencies contains mutable non-thread-safe state.
Fix: Make shared state immutable or synchronized, change the lifetime to match ownership, and add concurrent tests plus runtime telemetry.
Best practices
- Keep one visible composition root and group cohesive registrations with feature-named extension methods.
- Use constructor injection for required collaborators and avoid provider lookups in business code.
- Inject abstractions at real replacement or infrastructure boundaries, not an interface for every class.
- Choose lifetimes from ownership and thread-safety, including every dependency captured by the service.
- Validate options on startup when invalid values make the application unsafe or unusable.
- Create and dispose one scope per logical background operation; never reuse a request scope across concurrent work.
- Enable provider validation in development and composition tests, then resolve real entry points and every variant.
- Keep constructors cheap, avoid async work during resolution, and let the container dispose the objects it creates.
Production checklist
- The composition root is small, feature registrations are discoverable, and application or domain code does not use a global service locator.
- Every service lifetime is justified by state, thread-safety, disposal, and the lifetimes of all captured dependencies.
- Web requests use framework scopes and every worker, message, job, or console operation creates and disposes an explicit scope.
- Required options are strongly typed, semantically validated, and fail startup when the application cannot operate safely.
- All entry points, keyed services, multiple implementations, and environment-specific registration branches are covered by graph tests.
- Container and framework-owned services have clear disposal ownership; disposable transients are not accumulated in the root provider.
- Singletons contain no unbounded tenant or request state and are safe for concurrent use.
- Published builds verify trimming or AOT assumptions, graceful shutdown, readiness, startup failure, and production configuration.
Common interview questions
What is a captive dependency?
It occurs when a longer-lived service, commonly a singleton, captures a shorter-lived dependency such as a scoped service and unintentionally extends its lifetime.
How do singleton, scoped, and transient lifetimes differ?
Singleton reuses one root-owned instance, scoped reuses one instance per logical scope, and transient creates an instance for each resolution; disposal still follows the provider or scope that created it.
Why should a background worker create scopes?
Hosted services are normally singleton, while operation services such as DbContext are scoped. One explicit scope per message or job preserves isolation and ensures timely disposal.
Is dependency injection the same as the dependency inversion principle?
No. DI is a composition technique; dependency inversion is a design principle that high-level policy should depend on abstractions rather than low-level details.
When are keyed services appropriate?
Use them when several implementations share a contract and selection is based on a stable key such as channel or tenant tier; centralize selection and test every supported key.
Why is injecting IServiceProvider often a smell?
It hides required dependencies, defers failures to runtime, encourages service location, complicates tests, and can resolve services from the wrong ownership scope.
What does ValidateOnBuild not guarantee?
It checks constructability for services it can validate, but it cannot prove semantic correctness, every runtime key or factory branch, thread safety, or production configuration.
Dedicated GitHub sample
Clone, run, test, and modify the focused implementation created for this guide.
Dependency Injection Lifetimes
A focused .NET 10 console sample demonstrating composition-root organization, validated options, singleton, scoped, and transient ownership, explicit operation scopes, keyed services, container validation, disposal, and deterministic tests.
- Run
dotnet run --project src/DependencyInjectionLifetimes- Test
dotnet test DependencyInjectionLifetimes.slnx