Câu hỏi phỏng vấn .NET Core
Câu hỏi

When to use Transient vs Scoped v...

Câu trả lời

In .NET Core, understanding when to use Transient, Scoped, and Singleton service lifetimes is crucial for efficient dependency management and application performance. Here’s a detailed explanation of each service lifetime and when to use them:

Transient Services

Definition: Transient services are created each time they are requested from the service container. This means a new instance of the service is created every time it is injected or requested.

Use Cases:

  • Stateless Services: Transient services are ideal for lightweight, stateless services where each operation requires a clean and independent instance. For example, services that perform simple calculations or generate random numbers.
  • Short-lived Operations: Use transient services for operations that do not need to maintain any state between different requests or operations.

Example:

services.AddTransient<IMyService, MyService>();

In this example, IMyService will be instantiated anew each time it is requested.

Scoped Services

Definition: Scoped services are created once per request. In a web application, this means a new instance is created for each HTTP request but is shared across that request.

Use Cases:

  • Request-specific Data: Scoped services are useful when you need to maintain state within a single request. For example, database contexts (like Entity Framework DbContext) are often registered as scoped because they need to maintain state and track changes within a single request.
  • Shared Data within a Request: Use scoped services when multiple components within the same request need to share data or communicate.

Example:

services.AddScoped<IMyService, MyService>();

In this example, IMyService will be instantiated once per HTTP request and shared within that request.

Singleton Services

Definition: Singleton services are created the first time they are requested and then reused for every subsequent request throughout the application's lifetime.

Use Cases:

  • Shared State: Singleton services are ideal for services that need to maintain state across the entire application, such as caching services, configuration settings, or logging services.
  • Expensive Initialization: Use singleton services for objects that are expensive to create and should not be recr...
senior

senior

Gợi ý câu hỏi phỏng vấn

entry

What is .NET Core?

junior

What is a .NET application domain?

senior

Why does .NET use a JIT compiler instead of just compiling the code once on the target machine?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào