When to use Transient vs Scoped v...
When to use Transient vs Scoped v...
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:
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:
Example:
services.AddTransient<IMyService, MyService>();
In this example, IMyService
will be instantiated anew each time it is requested.
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:
Example:
services.AddScoped<IMyService, MyService>();
In this example, IMyService
will be instantiated once per HTTP request and shared within that request.
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:
senior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào