Skip to content
Tutorials Center
My learning

Topics

Lesson 129 of 182 ยท Dependency Injection and Hosting

Dependency Injection

Learn dependency injection in C#: the idea, constructor injection, ServiceCollection, singleton, scoped and transient lifetimes, keyed services and captive dependencies.

Imagine a class OrderService that sends a confirmation email. The easiest way to write it is to create the sender inside: var sender = new SmtpEmailSender();. That works until you want to test OrderService without sending real emails, or switch to another provider, or give the sender a configuration it needs. Then you discover that OrderService is welded to one concrete class.

Dependency injection (DI) is the cure. Instead of creating its collaborators, a class receives them from outside, usually through its constructor. A small component called the container knows how to build objects and hands each class what it asks for. DI is built into modern .NET (ASP.NET Core, the generic host, background services and many libraries rely on it), so understanding it is not optional. This lesson explains the idea without any framework first, then shows Microsoft.Extensions.DependencyInjection, the three lifetimes, scopes, keyed services and the pitfalls that cause real production bugs. It builds on interfaces and polymorphism, constructors and disposal.

The idea in plain C#

Dependency injection is a design technique first and a framework second. Here it is with no container at all ("poor man's DI"). OrderService depends on an abstraction (IEmailSender), not on a concrete class, and whoever creates OrderService decides which implementation to use.

C# Injection by hand

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The benefit is already visible: OrderService has no idea which sender it gets, so tests are trivial and swapping providers touches only the wiring code. The word for this is inversion of control: the class no longer controls what it uses; its creator does.

As applications grow, wiring by hand becomes tedious: new A(new B(new C(config), logger), new D(...)). A DI container automates that. You register what each abstraction means once, and the container creates complete object graphs on request.

The built-in container

The package Microsoft.Extensions.DependencyInjection is part of the ASP.NET Core shared framework, so it works in our runner (as using Microsoft.Extensions.DependencyInjection;). The workflow has three steps:

  1. Register services in a ServiceCollection: AddSingleton, AddScoped or AddTransient.
  2. Build a ServiceProvider from the collection.
  3. Resolve services with GetRequiredService<T>(), or, much more often, let the container inject them into constructors.
C# Registering and resolving

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Notice that OrderService has a constructor parameter of type IEmailSender and nobody wrote new OrderService(...). The container looked at the constructor, saw it needs an IEmailSender, found the registration, created (or reused) the sender and passed it in. This is constructor injection, and it is the style you should use by default: dependencies are visible in the signature, required, and usable in tests.

GetRequiredService throws InvalidOperationException ("No service for type 'IGreeter' has been registered.") when a registration is missing; GetService returns null. Prefer the "Required" version so mistakes fail loudly.

Resolving services yourself with GetRequiredService is called the service locator pattern. In application code it hides dependencies and makes classes hard to test. Use it only at the "composition root", the one place near program start where the object graph is assembled. Everywhere else, take dependencies as constructor parameters.

Registration styles

There are several overloads of each AddXxx method, and they matter:

Registration Meaning
AddSingleton<IFoo, Foo>() When someone asks for IFoo, create a Foo.
AddSingleton<Foo>() Register the class as itself.
AddSingleton<IFoo>(sp => new Foo(sp.GetRequiredService<IBar>())) Use a factory lambda for custom construction.
AddSingleton<IFoo>(existingInstance) Use an object you already created (singleton only).
TryAddSingleton<IFoo, Foo>() Add only if nothing is registered yet (used by libraries).
AddSingleton(typeof(IRepo<>), typeof(Repo<>)) Open generic registration: IRepo<User> gets Repo<User>.

If you register several implementations of the same interface, a normal request gets the last one registered, and asking for IEnumerable<IFoo> gets all of them in registration order. That is how plugin-style designs work:

C# Many implementations, factories and open generics

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The IClock registration is a good pattern in general: wrapping "what time is it?" behind an interface lets tests control time. (.NET 8 added a built-in TimeProvider class for the same purpose; see dates and times.)

Lifetimes: singleton, scoped and transient

Registering a service also says how long an instance lives. This is the most important and most misunderstood part of DI.

  • Transient: a new instance every time the service is requested. Good for lightweight, stateless services.
  • Scoped: one instance per scope. In ASP.NET Core a scope is one HTTP request, so everything in the same request shares one scoped instance (for instance, a database context), while another request gets its own.
  • Singleton: one instance for the entire lifetime of the container. Good for caches, configuration and expensive shared objects. It must be thread-safe, because many requests use it at once.

You create scopes yourself with provider.CreateScope(). The following program makes the three lifetimes visible by giving each service a counter-based id.

C# Lifetimes in action

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Read the output line by line. The singleton keeps the same number in every line, in both scopes. The scoped service keeps its number inside one scope but changes when the second scope starts. The transient service gets a fresh number on every request. (The numbers come from one shared counter, so they also show the order in which instances were created.)

Which lifetime should you choose?

  • Does the service hold per-request state (current user, a unit of work, a database context)? Scoped.
  • Is it stateless and cheap, or must every consumer have its own copy? Transient.
  • Is it shared, thread-safe and long-lived (cache, HTTP handler pool, configuration)? Singleton.
  • When unsure, start with transient or scoped; making something singleton is a promise about thread safety that you must keep.

Disposal

The container owns what it creates. When you dispose a scope, it disposes every scoped and transient IDisposable it created in that scope; disposing the root provider disposes the singletons. Objects you pass in as ready-made instances are not disposed by the container.

C# Who disposes what

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

A classic bug is resolving a scoped or transient service from the root provider in a long-running program: the container keeps a reference until the root is disposed, so memory grows. Always resolve scoped services from a scope.

Keyed services (.NET 8)

Sometimes you have several implementations of one interface and need a specific one. Before .NET 8 people wrote factories or wrapper classes. Now you can register a service under a key and ask for it by key: AddKeyedSingleton<TService, TImpl>(key) and [FromKeyedServices(key)] on a constructor parameter, or GetRequiredKeyedService<T>(key).

C# Keyed services

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Keys can be any object (strings and enums are the usual choices). Keyed registrations are separate from normal ones: asking for a plain INotifier in this program would fail, because nothing was registered without a key.

Captive dependencies and scope validation

The most common serious DI bug is the captive dependency: a longer-lived service holds on to a shorter-lived one. A singleton that takes a scoped service in its constructor "captures" the first instance forever, so a database context meant for one request lives for the whole application and is shared across threads. The rule: a service may only depend on services with an equal or longer lifetime (transient may use anything; scoped may use scoped and singleton; singleton may use only singletons).

Development environments of ASP.NET Core turn on scope validation, which detects this at the moment of resolution. You can switch it on yourself with BuildServiceProvider(new ServiceProviderOptions { ValidateScopes = true, ValidateOnBuild = true }).

C# Detecting a captive dependency

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

With ValidateOnBuild, the container checks every registration when it is built, so the error appears at startup instead of in production under load. Fix it by making ReportCache scoped, or by making it ask for a factory (IServiceScopeFactory) and create a short scope for each piece of work.

Never keep a reference to a scoped service in a static field or a singleton, and do not inject IServiceProvider into ordinary classes to dodge a lifetime error. Both hide the very problem the container is trying to tell you about.

Constructor choice, circular dependencies and design

When a class has several public constructors, the container picks the one with the most parameters it can satisfy. Circular dependencies (A needs B, and B needs A) cannot be built and throw an InvalidOperationException that spells out the cycle; they are a design smell. The usual fix is to extract the shared part into a third class or to depend on an event or callback.

Good habits:

  • Depend on abstractions that you own (IEmailSender), not on framework types everywhere.
  • Keep constructors small. More than four or five dependencies usually means the class does too much (see object design).
  • Never do work in constructors. Injection builds objects eagerly, so constructors should only store their arguments.
  • Prefer constructor injection over properties or method injection. Primary constructors (primary constructors lesson) make it concise.
  • Register at one place. A single AddMyFeature(this IServiceCollection services) extension method per feature keeps Program.cs readable.
  • Do not use DI for everything. Simple data objects and records need no container.

Dependency injection also does not mean you must have an interface for each class. Introduce an interface when there are (or will be) several implementations, when you want to fake a slow or external dependency in tests, or when you want to hide details across a boundary.

In ASP.NET Core and the generic host (see the generic host), the container is created for you: you only call builder.Services.AddXxx(...), and controllers, endpoints and background services get their dependencies automatically.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the main benefit of constructor injection?

    A class that receives its dependencies does not decide which implementations it uses. That makes the dependencies visible in the signature and easy to replace in tests.
  2. 2. In a web app, what does a scoped service give you?

    Scoped services are created once per scope. In ASP.NET Core a scope matches one HTTP request, so all services in that request share the instance.
  3. 3. You register two implementations of IRule. What does GetRequiredService<IRule>() return?

    A single-service request returns the last registration. Ask for IEnumerable<IRule> to get all of them in registration order.
  4. 4. What is a captive dependency?

    The singleton keeps the first scoped instance alive for the whole application, so the scoped service no longer behaves as scoped, and may be used from many threads. ValidateScopes and ValidateOnBuild detect it.
  5. 5. Which call asks for a service that was registered with a key?

    Keyed registrations are looked up with GetRequiredKeyedService or the [FromKeyedServices] attribute. A plain GetRequiredService does not see them.

Summary

  • Dependency injection means a class receives its collaborators instead of creating them; it makes code testable and flexible.
  • Microsoft.Extensions.DependencyInjection registers services in a ServiceCollection, builds a ServiceProvider and resolves object graphs for you.
  • Prefer constructor injection; use GetRequiredService only at the composition root.
  • Transient creates an instance per request for the service, scoped one per scope (for example per HTTP request), singleton one for the whole application.
  • Resolve scoped services from a scope, and know that the container disposes what it creates.
  • Keyed services (AddKeyedSingleton, [FromKeyedServices]) choose between several implementations of one interface.
  • Avoid captive dependencies: a service may depend only on equal or longer lifetimes. Turn on ValidateScopes and ValidateOnBuild to catch mistakes early.

Next: Configuration and Options