.NET

Dependency Injection

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

24 câu hỏi phỏng vấn·
Mid-Level
1

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

Câu trả lời

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?

Câu trả lời

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?

Câu trả lời

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 câu hỏi phỏng vấn

Nắm vững .NET cho lần phỏng vấn tiếp theo

Truy cập tất cả câu hỏi, flashcards, bài kiểm tra kỹ thuật, bài tập code review và mô phỏng phỏng vấn.

Bắt đầu miễn phí