Skip to content
Learn Netverks

Lesson

Step 15/36 42% through track

dependency-injection-intro

Dependency injection intro

Last reviewed May 28, 2026 Content v20260528
Track mode
server_compiled
Means
Compiled runner
Reading
~1 min
Level
beginner

This lesson

An orientation to the ASP.NET track—how the server playground works, core vocabulary, and what you will practice next.

You need a clear map of the ASP.NET track so middleware, dependency injection, and the .NET project layout do not feel like magic.

You will apply Dependency injection intro in contexts like: Line-of-business APIs, intranets, BFF layers, and cloud-hosted services on Linux or Windows.

Write C# (top-level or Program class), click Run on server—the dev runner uses dotnet build/run on a temp net8 project (requires .NET SDK; LEARNING_RUNNER_ENABLED=true). Also read the interview prep blocks.

After HTML fundamentals and basic programming concepts—before or alongside SQL.

ASP.NET Core includes a built-in DI container. Register services in Program.cs; the framework injects them into controllers, Razor Pages, and middleware via constructors.

Registration lifetimes

  • Transient — new instance every time requested
  • Scoped — one per HTTP request (typical for DbContext)
  • Singleton — one for app lifetime (caches, config readers)

Example

builder.Services.AddScoped<IEmailSender, SmtpEmailSender>();

public class AccountController : Controller {
    private readonly IEmailSender _email;
    public AccountController(IEmailSender email) => _email = email;
}

Important interview questions and answers

  1. Q: Why Scoped for DbContext?
    A: One context per request aligns with unit of work; sharing across requests causes threading and stale data bugs.
  2. Q: Captive dependency?
    A: Singleton holding Scoped service—lifetime mismatch; fix by adjusting registrations or using factories.

Self-check

  1. Which lifetime fits IEmailSender per request?
  2. Why inject interfaces instead of concrete classes?

Pitfall: Registering DbContext as Singleton causes threading bugs—always Scoped. Never inject Scoped services into Singleton without a factory.

Interview prep

Why Scoped for DbContext?

One DbContext per HTTP request aligns with unit of work—sharing across requests causes threading issues and stale tracked entities.

Interview tip Lesson completion confidence

Can you explain this lesson in 30 seconds without reading notes?

Not saved yet.

Playground

Runs on the configured server runner (dev: npm run runner with LEARNING_RUNNER_ENABLED=true). Output appears below the editor.

Check yourself

Multiple choice — immediate feedback.

Discussion

Past discussion is visible to everyone. Only logged-in users can post comments and replies.

Starter discussion topics

  • Scoped lifetime?
  • Register interface how?

Sign up or log in to post comments and sync lesson progress across devices.

No discussion yet. Be the first to ask a question.

Jump