asp.net phân tích ngắn gọn các loại IServiceCollection
- User
asp.net phân tích ngắn gọn các loại IServiceCollection
Assistant
IServiceCollection trong ASP.NET Core có các loại registration chính sau:
Transient - Tạo instance mới mỗi lần request
services.AddTransient<IService, Service>()- Phù hợp cho lightweight, stateless services
Scoped - Một instance cho mỗi HTTP request
services.AddScoped<IService, Service>()- Mặc định cho Entity Framework DbContext
- Phù hợp cho services cần maintain state trong request
Singleton - Một instance duy nhất cho toàn bộ application
services.AddSingleton<IService, Service>()- Phù hợp cho expensive-to-create objects, caching services
- Cần thread-safe
Các phương thức khác:
TryAdd*()- Chỉ register nếu chưa tồn tạiReplace()- Thay thế registration hiện cóRemoveAll()- Xóa tất cả registrations của type
Lưu ý quan trọng:
- Singleton không nên depend vào Scoped/Transient
- Scoped không nên depend vào Transient có state
- Memory leaks có thể xảy ra nếu Singleton giữ reference đến Scoped services
Việc chọn đúng lifetime giúp tối ưu performance và tránh các vấn đề về memory, concurrency.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.