Dependency injection

Dependency injection is a container that builds the objects of a program from a list of registrations. A class names its dependencies in its constructor, the container passes them, and the class never creates them. The container is in the ASP.NET Core shared framework, so a console app reaches it without NuGet and without the network.

ServiceCollection

A ServiceCollection takes the registrations, and BuildServiceProvider makes the container. A registration maps an interface to a class, and the constructor of the class receives the rest:

using Microsoft.Extensions.DependencyInjection; var services = new ServiceCollection(); services.AddSingleton<IClock, FixedClock>(); services.AddScoped<Report>(); services.AddTransient<Line>(); using var provider = services.BuildServiceProvider(); using (var scope = provider.CreateScope()) { var report = scope.ServiceProvider.GetRequiredService<Report>(); Console.WriteLine(report.Describe()); var same = scope.ServiceProvider.GetRequiredService<Report>(); Console.WriteLine($"scoped same {ReferenceEquals(report, same)}"); } var first = provider.GetRequiredService<IClock>(); var second = provider.GetRequiredService<IClock>(); Console.WriteLine($"singleton same {ReferenceEquals(first, second)}"); var line1 = provider.GetRequiredService<Line>(); var line2 = provider.GetRequiredService<Line>(); Console.WriteLine($"transient same {ReferenceEquals(line1, line2)}"); interface IClock { string Now { get; } } sealed class FixedClock : IClock { public string Now => "2024-03-10 09:30"; } sealed class Report(IClock clock) { public string Describe() => $"report at {clock.Now}"; } sealed class Line { public int Quantity { get; set; } = 1; }

dotnet run

report at 2024-03-10 09:30
scoped same True
singleton same True
transient same False

The container created the clock, passed it to the constructor of Report and the report printed the fixed time. The second resolution inside the same scope returned the same object, because a scoped registration lives as long as its scope. The types follow the statements in the same listing, which is what the compiler requires of a top-level program:

The primary constructor of Report is the one the container used, and no attribute or registration of the parameters was needed. The container reads the constructor of the class it was asked for and resolves the parameter types from the registrations it has.

Singleton, scoped and transient

The lifetime is the decision a registration makes:

A singleton must not depend on a scoped or a transient service, because it would capture the first one for ever; the container checks this at build time when ValidateScopes is on, which BuildServiceProvider(new ServiceProviderOptions { ValidateScopes = true }) sets. A database connection is scoped, a configuration object is a singleton, and a short-lived object that carries state for one operation is transient.

Several implementations

A registration may be repeated, and GetServices returns all of the implementations in registration order. A single GetRequiredService returns the last one:

using Microsoft.Extensions.DependencyInjection; var services = new ServiceCollection(); services.AddSingleton<INotifier, EmailNotifier>(); services.AddSingleton<INotifier, SmsNotifier>(); using var provider = services.BuildServiceProvider(); foreach (var notifier in provider.GetServices<INotifier>()) { Console.WriteLine(notifier.Name); } var one = provider.GetRequiredService<INotifier>(); Console.WriteLine($"one {one.Name}"); interface INotifier { string Name { get; } } sealed class EmailNotifier : INotifier { public string Name => "email"; } sealed class SmsNotifier : INotifier { public string Name => "sms"; }

dotnet run

email
sms
one sms

Two notifiers, in the order they were registered, and the single resolution gave the last one. A program that wants every implementation takes IEnumerable<T> in a constructor and the container fills it; that is how a list of handlers or validators is assembled without a switch in the caller.

Where the package is

The types are in the ASP.NET Core shared framework, and a console project sees them when its project file adds the framework reference:

<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>net10.0</TargetFramework> <Nullable>enable</Nullable> <ImplicitUsings>enable</ImplicitUsings> </PropertyGroup> <ItemGroup> <FrameworkReference Include="Microsoft.AspNetCore.App" /> </ItemGroup> </Project>

On a machine with the network the same API is one NuGet package, Microsoft.Extensions.DependencyInjection, which a project adds with dotnet add package; that route needs the feed, which this container does not have. The framework reference resolves against /usr/lib/dotnet/shared/Microsoft.AspNetCore.App/10.0.15, which is installed here, and the build is offline.

Exercises

  1. Change the report to singleton and read the validation error of ValidateScopes.
  2. Register a third notifier and confirm the order.
  3. Take IEnumerable<INotifier> in the constructor of a class and print the count.
  4. Resolve a type that was never registered and read the exception.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does ServiceCollection hold?

    Answer

    The registrations the container builds objects from

    BuildServiceProvider turns the registrations into the container.

  2. What does AddSingleton register?

    Answer

    One instance for the whole container

    The two clock resolutions were the same object.

  3. A scoped service is resolved twice inside one scope. What is returned?

    Answer

    The same instance both times

    The measured scope printed scoped same True for its two resolutions.

  4. What does AddTransient register?

    Answer

    A new instance on every resolution

    The two lines were different objects, as the measured False showed.

  5. What does a scope group?

    Answer

    Scoped services that live as long as the scope

    Two resolutions of a scoped service in one scope are the same object.

  6. A transient service is resolved twice. What is returned?

    Answer

    Two different instances

    The measured transient pair compared False with ReferenceEquals.

  7. What does GetServices<T>() return?

    Answer

    Every registration of T in registration order

    The measured output printed email and then sms.

  8. Two implementations of INotifier are registered and one is resolved with GetRequiredService. Which one comes back?

    Answer

    The last registration

    The measured single resolution printed sms, the second registration.

  9. Why must a singleton not depend on a scoped service?

    Answer

    It would capture the first scoped instance for ever

    A singleton lives longer than a scope, so the captured instance would outlive its scope.

  10. How does a console project see Microsoft.Extensions.DependencyInjection here?

    Answer

    A FrameworkReference to Microsoft.AspNetCore.App in the project file

    The shared framework is installed and the reference is offline; the NuGet package is the other route.

The code on this page was built with the .NET SDK 10.0.303 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev