.NET Dependency Injection (DI) Lifetimes

0.0(0)
Studied by 0 people
call kaiCall Kai
learnLearn
examPractice Test
spaced repetitionSpaced Repetition
heart puzzleMatch
flashcardsFlashcards
GameKnowt Play
Card Sorting

1/10

encourage image

There's no tags or description

Looks like no tags are added yet.

11 Terms

1
New cards

What is the Transient service lifetime in .NET DI?

A new instance of the service is created every single time it is requested from the DI container.

2
New cards

How do you register a Transient service in ASP.NET Core?

Using builder.Services.AddTransient

3
New cards

When should you use a Transient service lifetime?

For lightweight, stateless services that require no shared state across operations or threads.

4
New cards

What is the Scoped service lifetime in .NET DI?

A single instance of the service is created once per client request or operation such as an HTTP request.

5
New cards

How do you register a Scoped service in ASP.NET Core?

Using builder.Services.AddScoped

6
New cards

When should you use a Scoped service lifetime?

For stateful per-request operations like Entity Framework DbContext, Unit of Work, or request-specific context.

7
New cards

What is the Singleton service lifetime in .NET DI?

A single instance is created the first time it is requested and stays alive for the entire application lifetime.

8
New cards

How do you register a Singleton service in ASP.NET Core?

Using builder.Services.AddSingleton

9
New cards

When should you use a Singleton service and what must you be careful of?

Use for shared thread-safe state such as caching or clocks; ensure thread-safety and avoid injecting shorter-lived services.

10
New cards

What is a Captive Dependency in .NET Dependency Injection?

A bug occurring when a longer-lived service like a Singleton holds a reference to a shorter-lived service like a Scoped or Transient service.

11
New cards

Why are Captive Dependencies dangerous in web applications?

The Scoped service is kept alive indefinitely by the Singleton, causing memory leaks, stale data, and multi-threading bugs across HTTP requests.