.NET

Dependency Injection

Service lifetimes (singleton, scoped, transient), service registration, IServiceProvider, best practices

24 perguntas de entrevistaยท
Mid-Level
1

What is the main difference between Singleton, Scoped, and Transient lifetimes?

Resposta

Singleton creates a single instance for the entire application lifetime, Scoped creates one instance per HTTP request (or scope), and Transient creates a new instance every time it's injected. These lifetimes determine when and how many times the DI container instantiates a service. Use Singleton for stateless shared services, Scoped for request-bound services (like DbContext), and Transient for lightweight stateless services.

2

Which lifetime should be used to register an Entity Framework Core DbContext?

Resposta

DbContext should be registered with Scoped lifetime because it's not thread-safe and maintains entity tracking state. Each HTTP request should have its own DbContext instance to avoid concurrency issues. Registration is done with AddDbContext which automatically configures Scoped lifetime. Using Singleton would cause concurrency errors, and Transient would waste resources by creating too many instances.

3

How to register a service with an interface and its implementation?

Resposta

Service registration is done with AddSingleton, AddScoped, or AddTransient methods by specifying the interface as the service type and the concrete class as the implementation. The syntax is services.Add{Lifetime}<IInterface, Implementation>(). This approach respects the dependency inversion principle and facilitates testing by allowing implementation substitution. The DI container will automatically resolve the concrete implementation when injecting the interface.

4

When should AddSingleton be preferred over AddScoped?

5

What is the role of IServiceProvider in the DI system?

+21 perguntas de entrevista

Domine .NET para sua proxima entrevista

Acesse todas as perguntas, flashcards, testes tecnicos, exercicios de code review e simuladores de entrevista.

Comece gratis