Catalog My learning Blog
Full-Stack Developer Course: React, .NET and SQL Server · Phase 1 · Lesson 8 · 6 min read

.NET Dependency Injection vs Angular DI

On this page
  1. Learning Objective
  2. Concept Explanation
  3. Worked Example: A Console Host with an Injected Clock and Notifier
  4. Real-World Examples
  5. Review Questions & Answers

Learning Objective

Explain inversion of control and constructor injection, register services with transient, scoped and singleton lifetimes, resolve them from the built-in .NET container, and compare the model directly with Angular's injector so it feels familiar rather than foreign.

Concept Explanation

Dependency injection is a simple idea: a class does not create the things it depends on, it asks for them in its constructor, and something else supplies them. If you have written an Angular service that lists HttpClient in its constructor, you have already used it. The benefit is that the class depends on an abstraction, such as an interface, instead of a specific implementation. That makes it easy to swap a real email sender for a fake one in tests, to change a storage technology without touching business logic, and to see at a glance what a class needs, because the constructor lists it.

.NET ships a container in the package Microsoft.Extensions.DependencyInjection, and ASP.NET Core is built around it. You register services in a ServiceCollection, choosing an interface, an implementation, and a lifetime, then the container builds the object graph for you on demand. Registering AddSingleton of IClock, SystemClock means whenever a constructor asks for an IClock, hand it a SystemClock. If SystemClock itself needs other services in its constructor, the container resolves those too. You almost never call the container directly; you declare constructor parameters and let it work.

Lifetimes decide how long an instance lives, and choosing them correctly matters for both correctness and security. A transient service is created every time it is requested. A scoped service is created once per scope, which in a web application means once per HTTP request, and it is the right choice for anything holding request-specific state such as a database context or the current user. A singleton is created once for the whole application and shared by every request at the same time, so it must be thread-safe and must never hold per-user data. Angular has the same ideas: providedIn root behaves like a singleton, and providers at a component level create instances that live with that component.

The container also enforces good structure. Registrations live in one place, the composition root, near the program entry point. Classes do not reach into the container to fetch things on their own, an approach called the service locator pattern, because it hides dependencies and defeats testing. Prefer narrow interfaces so a class receives only the capabilities it needs, which is the principle of least privilege applied to code: a report generator that only needs to read data should be given a read-only interface, not the whole database context. Since .NET 8 there is also a built-in TimeProvider abstraction, so you inject the clock and never call DateTime.UtcNow directly in logic you want to test.

IdeaAngular.NET
Declare a dependencyConstructor parameter or inject()Constructor parameter
Register globallyprovidedIn: 'root'services.AddSingleton
Per-request or per-component instanceComponent-level providersservices.AddScoped
New instance every timeProvider with a factoryservices.AddTransient
Abstraction as tokenInjectionToken or abstract classInterface
Where wiring livesModules, providers arraysProgram.cs, the composition root

Worked Example: A Console Host with an Injected Clock and Notifier

The example registers a service, an abstraction and the built-in time provider in a generic host, then resolves the service. A test at the end swaps in a fake clock, which is the payoff of the whole pattern.

C#
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

public interface INotifier { Task NotifyAsync(string message); }

public sealed class ConsoleNotifier : INotifier
{
    public Task NotifyAsync(string message)
    {
        Console.WriteLine(message);
        return Task.CompletedTask;
    }
}

public sealed class ReminderService(TimeProvider clock, INotifier notifier)
{
    public Task RemindAsync(string task, DateTimeOffset due)
    {
        var overdue = clock.GetUtcNow() > due;
        return notifier.NotifyAsync(overdue ? $"OVERDUE: {task}" : $"Upcoming: {task}");
    }
}

// Program.cs: the composition root.
var builder = Host.CreateApplicationBuilder(args);
builder.Services.AddSingleton(TimeProvider.System);      // one shared clock
builder.Services.AddTransient<INotifier, ConsoleNotifier>();
builder.Services.AddScoped<ReminderService>();           // one per scope (per request on the web)

using var host = builder.Build();
using var scope = host.Services.CreateScope();
var reminders = scope.ServiceProvider.GetRequiredService<ReminderService>();
await reminders.RemindAsync("Ship the report", DateTimeOffset.UtcNow.AddDays(1));
C#
// Test: no real clock, no real console. Requires Microsoft.Extensions.TimeProvider.Testing.
public class ReminderServiceTests
{
    private sealed class CapturingNotifier : INotifier
    {
        public List<string> Messages { get; } = new();
        public Task NotifyAsync(string message) { Messages.Add(message); return Task.CompletedTask; }
    }

    [Fact]
    public async Task Past_due_tasks_are_marked_overdue()
    {
        var clock = new FakeTimeProvider(new DateTimeOffset(2026, 1, 10, 0, 0, 0, TimeSpan.Zero));
        var notifier = new CapturingNotifier();
        var service = new ReminderService(clock, notifier);

        await service.RemindAsync("Pay invoice", new DateTimeOffset(2026, 1, 9, 0, 0, 0, TimeSpan.Zero));

        Assert.Equal("OVERDUE: Pay invoice", notifier.Messages.Single());
    }
}

The service never mentions DateTime.UtcNow or Console, so the test controls time and captures output without any special tooling. That same swap, a real dependency in production and a fake one in tests, is how you will test API endpoints without a real database or identity provider later.

Registrations in the composition root tell the container how to build ReminderService and its dependencies. A test registers a fake clock in place of the real one.
Registrations in the composition root tell the container how to build ReminderService and its dependencies. A test registers a fake clock in place of the real one.

Real-World Examples

  • Dependency injection has been built into ASP.NET Core since version 1.0 in 2016, which was a deliberate break from the older ASP.NET where teams had to choose and bolt on a third-party container. Because every framework component, from logging to authentication to Entity Framework Core, resolves through the same container, replacing or decorating any of them is a matter of registering a different implementation.
  • The Microsoft.Extensions.DependencyInjection package is independent of the web stack, so background workers, console tools and Azure Functions use exactly the same container and registration syntax as web APIs. Skills you build here carry over to every kind of .NET application.
Key TakeawaysConstructor injection means classes declare what they need and the composition root supplies it, exactly like Angular services. Pick lifetimes carefully, with scoped for per-request state and singleton only for thread-safe shared data, inject abstractions such as TimeProvider and narrow interfaces so tests can substitute them, and keep all wiring in one place.

Review Questions & Answers

A transient instance is created each time it is requested, so two consumers get different objects. A scoped instance is created once per HTTP request and shared by everything that participates in that request, which suits state like the current database context. A singleton is created once and shared by all requests concurrently for the life of the process, so it must be thread-safe and must not hold user-specific data.

It hides what a class needs, because the dependencies are no longer visible in the constructor, and it makes testing awkward because the class needs a container to run. It also lets code request any service at any time, which invites tangled dependencies. Constructor injection keeps dependencies explicit, verifiable, and easy to replace.

A class only receives the capabilities it is meant to use, so a mistake or a compromise in that class cannot invoke unrelated powerful operations. A component that needs to read products gets a read-only reader rather than a context that can also delete data or change permissions. It is least privilege applied at the code level, and it also makes code reviews simpler because the constructor shows the class's reach.

Code that reads the system clock directly cannot be tested deterministically, because its behavior changes with the real time. Injecting TimeProvider lets tests supply a fake whose time you set and advance, so logic about deadlines, expiry, and tokens can be verified exactly. It also centralizes time, which helps when auditing time-sensitive security features like token lifetimes.